Tutorial Django- Class based view #3 : Authentication in Django and Urls Protection globally and specifically

in #utopian-io6 years ago (edited)

Repository

https://github.com/python

What Will I Learn?

  • Authentication in Django
  • URLs protection globally and specifically

Requirements

  • Basic Python
  • Install Python 3
  • Install Django

Resources

Difficulty

Basic

Tutorial Content

hi everyone, we will continue our learning about class-based view. In the previous tutorial we learned how to conceptualize class-based view and how it is implemented, now we will learn how to protect pages in class-based view. In actual implementation, of course, when we create a page there are times when we want the page to be in actual implementation, of course when we create a page when we want the page not to be accessed by the user. Therefore we will learn how to protect the page. for those of you who don't understand what is Django ?, I suggest you follow the previous tutorials that are in the curriculum section.

Page protection in Django

We can use special routing protection or overall routing, we will simulate the two conditions. All we have to do first is install python migrate. So later I will use this protection page to create a simple authentication system to protect a page so that it cannot be accessed by the user. We can install python migrate like this:

Install python migrate

python manage.py migrate

Screenshot_4.png
If we look at the picture above we have successfully migrated:
Apply all migrations : admin, auth, contenttypes, sessions

  • Authentication system in Django

As we have seen at the top when we install python migrate that means we have installed several modules. well, the module that we will use is auth. we will use the Django authentication system to protect our pages. We can see the code below, The code below is an advanced code from the previous tutorial series, so you can follow the previous tutorial for a more detailed explanation.

urls.py

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

from .views import IndexView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('tutorial/', IndexView.as_view())

    path('accounts/', include('django.contrib.auth.urls'))
]
  • import include module: We will import the include function so that it can be used to include auth from Django.

  • create auth : To activate the auth system on Django we can do it this way path('accounts/', include('django.contrib.auth.urls')). I will make a new routing that is accounts/. by using include ('django.contrib.auth.urls') then the url will be automatically directed to accounts/login. For more details, we can see in the picture below:

ezgif.com-video-to-gif (4).gif

Screenshot_7.png

We see in the picture above the URL did not find the registration/login.html file. when we make auth, we will automatically be directed to the file. for that, we make the file so that it can be accessed.

  • Create login page

Now we will create a login page, but we won't really do a login because we don't learn about the database in python. but we will simulate how to protect pages in Django. The following is a simple login page that we created at registration / login.html.

registration/login.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <h1>Login</h1>
    <form>
        {% csrf_token %}
        {{ form.as_p}}
        <button type="button" name="button">Submit</button>
    </form>

</body>
</html>

Screenshot_6.png

Of course, we will use the {% csrf_token %} and to simplify the login form, I will use {{ form.as_p}} to generate the form.

Implement protection page

We can choose whether to use all URL protection in our application or protect the URL that we consider important. for that I will divide it into two types as below:

  • Use protection on one page

To protect in a special URL we need to import the login_required function. The following is an example of the code:

urls.py

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

from .views import IndexView

from django.contrib.auth.decorators import login_required

urlpatterns = [
    path('admin/', admin.site.urls),
    path('tutorial/', login_required(IndexView.as_view())),
      path('accounts/', include('django.contrib.auth.urls'))
]
  • To protect a page with an authentication system from Django we can use the login_required function. but we have to import it first like this from django.contrib.auth.decorators import login_required.

  • To use it we can use the login_requeired function to wrap the template that we have created for example like the following path('tutorial/', login_required(IndexView.as_view())),. login_required(template). For more details, we can see in the picture below:

ezgif.com-video-to-gif (5).gif

We can see in the picture above we try to access the route 'tutorial/' but because the routing has been protected we will be directed to the login page.

  • Use page protection globally

We have implemented how to protect per page, now how do we type we want to protect all routing in our application or in our routing class (views.py), here's how:

views.py

from django.http import HttpResponse
from django.views.generic import TemplateView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

@method_decorator(login_required, name='dispatch')

class IndexView(TemplateView):
    template_name = 'index.html'
    def get(self, request):
       return HttpResponse("Successed !!")

    def post(self, request):
        return HttpResponse("You are on the POST method !!")
  • The use of protection in the class is not much different from the use in the routing section per page. The striking difference is using @method_decorator.

  • To use @method_decorator we must import it first like this from django.utils.decorators import method_decorator.

  • We can define the login_required function in @method_decorator as follows @method_decorator(login_required, name='dispatch'). For the second parameter is name = 'dispatch'. name = 'dispatch' is like middleware on django authentication. If there is no error then we can see the results as shown below:

ezgif.com-video-to-gif (6).gif

We have learned how to protect pages with Django authentication, we can protect pages that users will access, this way we have control of pages that can be accessed by users or not, this tutorial teaches a simple concept of Django authentication. You can explore more about this topic. I hope this tutorial can help you. thank you.

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 #5: Web development with python #5 : Session in flask and Login and Logout system

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

Tutorial Django - Class based views #1 : Installation and configuration Django, Using a template system

Tutorial Django - Class based view #2 : Use Class based view method and Get and Post method

Proof of work done

https://github.com/milleaduski/class-based-view-django

Sort:  

Thank you for your contribution @duski.harahap.
After reviewing your tutorial, we suggest the following points below:

  • We suggest you put comments in the code sections. It helps users a lot to realize what you are developing.

  • Django is well documented on the web. We suggest that you put a more innovative Django subject that is of great use to the open source community.

Thank you for your work in developing this tutorial.

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!

Coin Marketplace

STEEM 0.18
TRX 0.16
JST 0.031
BTC 62471.79
ETH 2621.42
USDT 1.00
SBD 2.56