When we talk about views in Django, views are the core part of Django which serves as the main place to process the incoming request.
Basically, we write out the view function in the views.py
file, but we can write this function on a different file as well. We just need to map this function with our URL configuration.
Creating a function based view is quite easy, we just need to create a normal python function with first parameter request
as mandatory, because this parameter is the Request Object
which we may need on our views. Request Objects contains various useful information about the requests like request method
,request data
and so on.
Also, this function based view must return an HttpResponse
or its valid subclasses which is very important since a HTTP Response contains various information which Django configures automatically.
Basic Example;
from django.http import HttpResponse
def dashboard_view(request):
# write your view processing logics here
return HttpResponse("Welcome to Dashboard")
To return a template we use
render()
function instead ofHttpResponse()
, but if you look into the code of this shortcutrender()
function it usesHttpResponse()
at the end. Django Github : django.shortcuts.render()
Allow only specific request method on views
When we work with views, we sometime need a way to allow only specific request method like GET
or POST
according to our need. The basic way to perform this can be by doing if/else check on the view itself
from django.http import HttpResponse
def dashboard_view(request):
if request.method == 'GET'
return HttpResponse("Welcome to Dashboard")
else:
# send status= 405 which means method not allowed
return HttpResponse(status=405)
But we can perform this with help of view decorator require_http_methods
from django.http import HttpResponse
from django.views.decorators.http import require_http_methods
@require_http_methods(["GET"])
def dashboard_view(request):
# only GET allowed
return HttpResponse("Welcome to Dashboard")
Adding extra parameter on view to capture URL values
If you are capturing values from URL then your view function should have parameter to accept this values
# urls.py
urlpatterns = [
path('/profile/<str:username>/', user_profile_detail_view) # we used <str> path converter and assigned the value to username
]
# views.py
def user_profile_detail_view(request, username):
# do something with the username
pass
Have a detail read about URL design and URL values capturing at: URL designing and URL kwargs in Django