A Basic Application – Django

As we discussed in the previous blog, Django divides all of its web applications into ‘projects’. Each project can be further divided into individual applications that can be developed and then integrated into the root project.

In this blog, we will be building a very basic application using Django. Continuing the working directory of the previous blog where we had initialized our first application “appName” inside “projectName”.

The file appnameviews.py contains the code that determines what the user sees at a particular route. At first, it will look like this:

  from django.shortcuts import render
  # Create your views here.

A basic view might just return a simple HttpResponse.

from django.http import HttpResponse
from django.shortcuts import render

#create your views here

def index(request):
	return HttpResponse("<h1> Hello World </h1>")  # HTML code to be rendered in basic view

To render this view, we have to specify what route it is at, to do so new urls.py must be created inside the appName directory (this is different from the project-level file of the same).
The Practise of creating separate urls.py file for each application makes it more simple and reusable in other projects.

Copy the below-given code in appName/urls.py

from django.urls import include, path

  from . import views # important to link all the view defination of application with corresponding urls

  urlpatterns = [
      path("", views.index),
 # "" Defines the empty route 

now our application is ready to launch, but before that we have to link our application to the project and to do so we have to edit the two important files in our root directory,
which should look like this:

  1. projectName/settings.py
# Application Defination :

2. projectName/urls.py

from django.contrib import admin
  from django.urls import include, path

  urlpatterns = [
      path("", include("appname.urls")),
      path("admin/", admin.site.urls)

The reason for this apparent complexity is to allow for routing amongst multiple different applications. This urls.py serves as the dispatch point for all those lower-level urls.py files.

To run the application, run python manage.py runserver.

In the next blog, we will learn how to render a custom HTML template in Django. ‘Till then Happy Coding :]

And for any related query, feel free to comment down your errors. =)

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s