Create A Simple Django App With Python

This blog post will explain how to create a simple django app with python. Django is a high-level Python web framework that helps with the development of websites. They are secure and easy to maintain. All the difficult stuff is already taken care of so someone can concentrate on building web applications. Components that are provided are reusable and are already provided with Django. Those components are a login screen, and a database connection with the operations create, read, update, and delete.

Create a django project named myproject.

django-admin startproject myproject

Navigate to the myproject directory and run this command to create an app named hello.

python manage.py startapp hello

Create a templates folder inside the myproject/hello folder, and create a HTML file named first.html.

<!DOCTYPE html>
<html>
<body>

<h1>Hello World!</h1>

</body>
</html>

In the file myproject/hello/views.py, add the code below.

from django.http import HttpResponse
from django.template import loader

def hello(request):
  template = loader.get_template('first.html')
  return HttpResponse(template.render())

Open the myproject/myproject/settings.py file and add the line below.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'hello'
]

Navigate to the myproject directory and run this command.

python manage.py migrate

In the file myproject/hello/urls.py, add the code below.

from django.urls import path
from . import views

urlpatterns = [
    path('hello/', views.hello, name='hello'),
]

In the file myproject/myproject/urls.py, add the code below.

from django.urls import include, path

urlpatterns = [
    path('', include('hello.urls'))
]

Navigate to the myproject directory and run this command to start the server.

python manage.py runserver

Run this command in a web browser.

http://127.0.0.1:8000/hello/

Leave a Reply