Django Views Unleashed Part 1

||
Posted 2 years, 9 months ago
||
Views 283
||
2 min read
0 reactions

In this tutorial , we are going to explore about Django views in depth.

Lets start,

Step 1:

Create Project 

django-admin startproject teckiy

Step 2:

We need to create the app as like below,

(env) PS C:\Training\teckiy> python .\manage.py startapp tutorial

Step 3:

Add the below code in tutorial/views.py file.

from django.http import HttpResponse

def home(request, *args, **kwargs):
    return HttpResponse('<h1>Welcome to Teckiy.com </h1>')

Step 3:

In order to navigate the URL, we have to add below line into teckiy/urls.py

from django.contrib import admin
from django.urls import path
from tutorial.views import index

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index)
]

Step 4:

Lets take a look on *args and **kwargs in views.

def index(request, *args, **kwargs):
    print(request.path, args , kwargs)
    return HttpResponse('<h1>Welcome to Teckiy.com </h1>')

Step 5:

In order to access the argument, lets add this teckiy/urls.py

from django.contrib import admin
from django.urls import path
from tutorial.views import index

urlpatterns = [
    path('admin/', admin.site.urls),
    path('<int:int>/', index)
]

Step 6:

Sometimes,we may need to return page not found instead of thorwing an error. For this Django has inbuilt method to access it.

from django.http import HttpResponse,HttpResponseNotFound

def index(request, *args, **kwargs):
    print(kwargs)
    if kwargs['int'] == 1:
        return HttpResponse('<h1>Welcome to Teckiy.com </h1>')
    return HttpResponseNotFound('<h1>Page not found</h1>')

Step 7:

Obviously, this is not appropriate way to render the HTML , and more over its looks very congested. Now we can take a look how to render using base.html

Lets create the template folder under tutorial/templates/tutorial/base.html project

def index(request, *args, **kwargs):
    print(kwargs)
    if kwargs['int'] == 1:
        return render(request,'tutorial/base.html',{})
    return HttpResponseNotFound('<h1>Page not found</h1>')

Now, we need to add the content in base.html

<h1>Welcome</h1>

Now its serves from tutorial/base.html

Next chapter, we will discuss more about Class Based Views in depth


0 reactions

Discussion


Looking for Freelancing Jobs
Joined on April 15, 2020


Latest Videos


Wanna Post Ad?
Reach a large group of audience by posting an ad about your business here. For more details
Drop us a Message