Tutorial Django- Class based view #2 : Use Class based view method and Get and Post method
Repository
What Will I Learn?
- Use Class based view method
- Request get and post method in Django
Requirements
- Basic Python
- Install Python 3
- Install Django
Resources
- Python - https://www.python.org/
- Flask - http://flask.pocoo.org/
- Django- https://www.djangoproject.com/
Difficulty
Basic
Tutorial Content
hi all, this time I will still discuss class-based view in Django. this tutorial is a continuation of the previous tutorial series, for those of you who don't know what Django is you can follow the previous tutorial in the curriculum section. In the previous tutorial, I discussed installation and configuration for the initial initialization of our project in Django and in the previous tutorial we also learned how to use templates in Django. Well, in this tutorial I will explain more about class-based views, so we just start this tutorial.
Metode class based views
As you saw in the previous tutorial, at the end of the tutorial we only use templates but haven't used the based views method. Well, in this section, we will really use the method. If we look at the previous tutorial we will call the template in the following way:
previous tutorial
urlpatterns = [
path('admin/', admin.site.urls),
path('tutorial/', TemplateView.as_view(template_name='index.html'))
]
If we look at the code above I only use TemplateView
but don't use the class based views method to render templates, Of course in this way we will be a little troubled if our code has become bigger and more complex. So with class-based views methods we can use the OOP concept in the template system used.
- Use class-based views
I will create a new file by being responsible for setting up the template system in our application. I will make the views.py file. For more details, we can see the code below:
views.py
from django.views.generic import TemplateView
class IndexView(TemplateView):
template_name = 'index.html'
If the previous tutorial is importing TemplateView in the urls.py then now we will import it in views.py because we will collect the templates in this file. We can import TemplateView like this
from django.views.generic import TemplateView
Then we will create a class named IndexView and pass TemplateView in this class
class IndexView(TemplateView)
and defined the file name to be renderedtemplate_name = 'index.html'
Index.html
<!DOCTYPE html>
<html>
<head>
<title> Python:: Class based view</title>
</head>
<body>
<h1>This is rendered from class based views</h1>
</body>
</html>
- Use in routing
We have made the class-based views file now we will use it in routing at urls.py. For more details, we can see the code below:
from django.contrib import admin
from django.urls import path
from .views import IndexView
urlpatterns = [
path('admin/', admin.site.urls),
path('tutorial/', IndexView.as_view())
]
Import Views.py : To use the class on views.py we have to import it, we can import it like this
from .views import IndexView
. IndexView is the class name in the views.py file, so the name must be matched to the class name that has been defined.Use in routing : to use it on the route we can use the class name and follow it with the
as_view()
method like this:path('tutorial/', IndexView.as_view())
. We can see the results as shown below:
We can see in the image above that the code becomes more structured by using classes methods, well because templates are rendered using the class-based views method, we can make functions in that class to be used repeatedly.
The Request method in Class-based views
- GET Method
In this section, we will learn about request methods in class-based views, as we have in the previous section when we access URLs with certain functions we do not specify what method to use. This can happen because TemplateView will automatically use the get method as default. But we can change it as we see in the code below:
from django.http import HttpResponse
from django.views.generic import TemplateView
class IndexView(TemplateView):
def get(self, request):
return HttpResponse("Success")
Import HttpResponse : To use the request method we need to import the
HttpRequest
function in the modulefrom django.http import HttpResponse
.Define get : Now we can define the
get ()
method with two parameters, namely mandatory, They are self and request. If you do not define these parameters then we will get an error like this:
- If there is no error I will try to return a simple response like the following
return HttpResponse("Success")
.
Even though we don't define the get function at the URL, django will automatically direct routing to the get function. Now we know how the get method works in django, Now we will see the post method. We will discuss it in the next section.
- POST Method
Now we will learn how the POST method works on Django, to make the POST method I will make a simple form just to do the POST method, here is the code:
Index.html
<!DOCTYPE html>
<html>
<head>
<title> Python:: Class based view</title>
</head>
<body>
<h1>This is form for submit </h1>
<form method="post">
{% csrf_token %}
<button type="submit" name="button">Submit</button>
</form>
</body>
</html>
We will not actually send data when using the post method. We need to pay attention to this page, we add {% csrf_token %}
to protect the page and don't forget to use the post method on the form <form method="post">
.then we will create a post method on views.py.
views.py
from django.http import HttpResponse
from django.views.generic import TemplateView
class IndexView(TemplateView):
template_name = 'index.html'
def post(self, request):
return HttpResponse("You are on the POST method !!")
In the post method, it is not different from the get method, this method also has two mandatory parameters. They are self and request. If there is no error then we will get results like the following:
We have learned how to conceptualize the request method in Django, the examples I gave are simple examples, besides returning HttpResponse you can do the logic you need before throwing a response or rendering a template. just get here my tutorial. hopefully useful, thanks.
Curriculum
- Web development with flask
Web developement with python #1 : Flask initialization and Routing system
Web development with python #2 : Templating jinja2 and Method POST on routing system
Web development with python #3 : Get method, Query parameter and Navigate Routing
Web development with python #4: Store cookie and Get cookie in template
Web development with python #6 : Use flash message and combine it with framework boostrap
- File in python
File in python #1 : Read file and Write file and Modes file
File in python #2 : The interaction between user input, Read CSV file
File in python #3 : Write CSV file, Read and Write JSON file
- Class-based views
Thank you for your contribution @duski.harahap.
After reviewing your tutorial, we suggest the following points below:
There are several online tutorials on the subject of Django explaining the get and post methods. However, your tutorial is well explained and will help less experienced users with Django.
We suggest you post comments in the code sections. It helps users a lot to realize what you are developing.
Thank you for your work in developing this tutorial. We are waiting for more tutorials.
Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.
To view those questions and the relevant answers related to your post, click here.
Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]
Thank you for your review, @portugalcoin! Keep up the good work!
Hi @duski.harahap!
Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server
Hey, @duski.harahap!
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!
Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).
Want to chat? Join us on Discord https://discord.gg/h52nFrV.
Vote for Utopian Witness!