Difference between revisions of "Python-Django/C2/Django--Authentication/English"
Pravin1389 (Talk | contribs) |
Nancyvarkey (Talk | contribs) |
||
(One intermediate revision by the same user not shown) | |||
Line 20: | Line 20: | ||
|| In this tutorial, we will learn to: | || In this tutorial, we will learn to: | ||
− | * Create a '''login''' | + | * Create a '''login functionality''' |
* Use '''Django’s built-in login''' and '''logout functions''' | * Use '''Django’s built-in login''' and '''logout functions''' | ||
Line 27: | Line 27: | ||
|| To record this tutorial, I am using | || To record this tutorial, I am using | ||
− | * '''Ubuntu Linux OS 16.04 | + | * '''Ubuntu Linux''' OS 16.04 |
− | * '''Python | + | * '''Python''' 3.5 |
* '''Python 3.4-venv''' or higher | * '''Python 3.4-venv''' or higher | ||
* '''gedit Text Editor '''and | * '''gedit Text Editor '''and | ||
− | * '''Firefox ''' | + | * '''Firefox web browser''' |
|- | |- | ||
Line 52: | Line 52: | ||
Press CTRl+ALT+T simultaneously | Press CTRl+ALT+T simultaneously | ||
− | || Let us open the '''terminal '''by pressing '''Ctrl | + | || Let us open the '''terminal '''by pressing '''Ctrl, Alt''' and '''T '''keys simultaneously on the keyboard. |
|- | |- | ||
Line 92: | Line 92: | ||
|| We are now in '''forms.py.''' | || We are now in '''forms.py.''' | ||
− | Next to the | + | Next to the '''class ArticleForm''', type the code as shown. |
− | Then let us import the '''AuthenticationForm''' | + | Then let us '''import''' the '''AuthenticationForm'''. |
|- | |- | ||
Line 100: | Line 100: | ||
'''class LoginForm''' | '''class LoginForm''' | ||
− | || Here we are specifying a custom '''form | + | || Here we are specifying a custom '''form class'''. |
|- | |- | ||
Line 112: | Line 112: | ||
'''from django.contrib.auth.forms import AuthenticationForm''' | '''from django.contrib.auth.forms import AuthenticationForm''' | ||
− | || To do that, we need to | + | || To do that, we need to '''import AuthenticationForm '''from '''django contrib auth forms module.''' |
|- | |- | ||
Line 120: | Line 120: | ||
'''password''' | '''password''' | ||
− | || '''Form fields | + | || '''Form fields username '''and '''password''' are declared here. |
|- | |- | ||
Line 128: | Line 128: | ||
'''forms.CharField(label="Password", max_length=30)''' | '''forms.CharField(label="Password", max_length=30)''' | ||
− | || ''' | + | || '''username '''and '''password '''are '''CharField'''. |
− | '''CharFields''' are rendered as text box on the''' web browser'''. | + | '''CharFields''' are rendered as a text box on the''' web browser'''. |
|- | |- | ||
Line 136: | Line 136: | ||
'''label="Username", max_length=30''' | '''label="Username", max_length=30''' | ||
− | || Here, we pass two '''arguments label '''and''' max_length''' for the ''' | + | || Here, we pass two '''arguments label '''and''' max_length''' for the '''character field.''' |
There are many other '''arguments''' available. | There are many other '''arguments''' available. | ||
Line 157: | Line 157: | ||
|- | |- | ||
|| Only narration | || Only narration | ||
− | || We have now created the '''Login | + | || We have now created the '''Login form'''. |
Next, let us create a new '''template login.html''' to display the '''form.''' | Next, let us create a new '''template login.html''' to display the '''form.''' | ||
|- | |- | ||
|| Switch to Terminal | || Switch to Terminal | ||
− | || Switch to '''terminal''' | + | || Switch to the '''terminal''' |
|- | |- | ||
|| [Terminal] | || [Terminal] | ||
Line 197: | Line 197: | ||
Highlight ‘’’<nowiki> {{ form.as_p }}</nowiki>''' | Highlight ‘’’<nowiki> {{ form.as_p }}</nowiki>''' | ||
− | || '''form.as_p '''will render the '''form fields''' wrapped in '''p tag.''' | + | || '''form.as_p '''will '''render''' the '''form fields''' wrapped in '''p tag.''' |
− | Here, we rendered the '''Login form''' from''' form dot py''' file using''' form.as_p''' | + | Here, we '''rendered''' the '''Login form''' from''' form dot py''' file using''' form.as_p''' |
|- | |- | ||
Line 209: | Line 209: | ||
|- | |- | ||
|| Switch to Terminal | || Switch to Terminal | ||
− | || Switch to '''terminal''' | + | || Switch to '''terminal'''. |
|- | |- | ||
|| [Terminal] | || [Terminal] | ||
Line 217: | Line 217: | ||
|| Let us now add the '''url''' for '''Login'''. | || Let us now add the '''url''' for '''Login'''. | ||
− | To do so, open the ''' | + | To do so, open the '''root URL''' file. |
Type''' gedit <space> mysite slash urls dot py <space> ampersand''' | Type''' gedit <space> mysite slash urls dot py <space> ampersand''' | ||
Line 240: | Line 240: | ||
] | ] | ||
− | || We are now in ''' | + | || We are now in '''root URL '''file which is under '''project mysite '''directory. |
Modify the code as shown here. | Modify the code as shown here. | ||
Line 249: | Line 249: | ||
'''{'template_name':'blog/login.html',authentication_form': LoginForm}''' | '''{'template_name':'blog/login.html',authentication_form': LoginForm}''' | ||
− | || | + | || It '''renders''' a template '''login.html '''under the '''Blog App''' directory. |
− | It also renders the '''authentication form''' which we created which is '''LoginForm.''' | + | It also '''renders''' the '''authentication form''' which we created, which is '''LoginForm.''' |
|- | |- | ||
|| [mysite/urls.py] Highlight | || [mysite/urls.py] Highlight | ||
Line 264: | Line 264: | ||
'''from blog.forms import LoginForm''' | '''from blog.forms import LoginForm''' | ||
− | || For that, we need to import two '''packages''' | + | || For that, we need to '''import''' two '''packages''' |
* '''Django Authentication view''' from '''django.contrib.auth ''' | * '''Django Authentication view''' from '''django.contrib.auth ''' | ||
Line 292: | Line 292: | ||
Scroll down to the bottom of the page. | Scroll down to the bottom of the page. | ||
− | + | In the last line, type the code as shown. | |
|- | |- | ||
|| [settings.py] Highlight | || [settings.py] Highlight | ||
'''LOGIN_REDIRECT_URL = '/blogs/get_blogs/'''' | '''LOGIN_REDIRECT_URL = '/blogs/get_blogs/'''' | ||
− | || When the user is authenticated, this will redirect to''' get underscore blogs''' page. | + | || When the '''user''' is '''authenticated''', this will redirect to''' get underscore blogs''' page. |
|- | |- | ||
|| Press Ctrl+S | || Press Ctrl+S | ||
Line 349: | Line 349: | ||
|| We are now in '''views.py''' file. | || We are now in '''views.py''' file. | ||
− | Add the line ''' | + | Add the line '''at the rate login_required <within brackets> login_url equal to <within double quotes within slash> login''' above all the '''view function''' as shown. |
|- | |- | ||
Line 359: | Line 359: | ||
'''Django''' comes with some'''built-in decorators''', like''' login_required'''. | '''Django''' comes with some'''built-in decorators''', like''' login_required'''. | ||
− | If a'''user '''is'''authenticated | + | If a'''user '''is'''authenticated, login_required decorator''' successfully executes the'''view function.''' |
− | If not, it redirects the'''user''' to the'''login URL''' | + | If not, it redirects the'''user''' to the'''login URL'''. |
|- | |- | ||
|| [views.py] Type: | || [views.py] Type: | ||
Line 377: | Line 377: | ||
<nowiki># Create your views here.</nowiki> | <nowiki># Create your views here.</nowiki> | ||
− | || | + | || In the '''import''' section, update the code as shown. |
|- | |- | ||
|| [views.py] Highlight | || [views.py] Highlight | ||
Line 384: | Line 384: | ||
'''from .forms import LoginForm''' | '''from .forms import LoginForm''' | ||
− | || | + | || Here we have imported |
'''login underscore required decorator''' from '''django.contrib.auth.decorator''' | '''login underscore required decorator''' from '''django.contrib.auth.decorator''' | ||
− | + | and '''LoginForm class''' from '''forms module.''' | |
|- | |- | ||
|| Press Ctrl+S | || Press Ctrl+S | ||
Line 415: | Line 415: | ||
|| In the new tab, move to '''my-django''' directory using the '''cd command.''' | || In the new tab, move to '''my-django''' directory using the '''cd command.''' | ||
− | Activate the '''virtual | + | Activate the '''virtual environment.''' |
|- | |- | ||
|| [Terminal tab 2] type cd mysite | || [Terminal tab 2] type cd mysite | ||
Line 429: | Line 429: | ||
|| Now, open a '''web browser.''' | || Now, open a '''web browser.''' | ||
− | In the address bar, type the '''URL''' as shown. | + | In the '''address bar''', type the '''URL''' as shown. |
Then press '''Enter.''' | Then press '''Enter.''' | ||
|- | |- | ||
|| [browser] | || [browser] | ||
− | || Here, we can see a '''login''' page with the fields for '''username''' and '''password.''' | + | || Here, we can see a '''login''' page with the '''fields''' for '''username''' and '''password.''' |
|- | |- | ||
|| [browser] | || [browser] | ||
Line 457: | Line 457: | ||
Pointing to the browser’s address bar | Pointing to the browser’s address bar | ||
− | || If the credentials are correct then we will be redirected to '''blogs/ | + | || If the credentials are correct then we will be redirected to '''blogs/get_blogs''' page. |
As we defined the '''Login Urls Redirect''' in '''settings.py''' file. | As we defined the '''Login Urls Redirect''' in '''settings.py''' file. | ||
Line 495: | Line 495: | ||
|- | |- | ||
|| '''{'next_page': '/login'},''' | || '''{'next_page': '/login'},''' | ||
− | || '''next_page''' | + | || '''next_page parameter''' determines the page to redirect after the '''user''' logs out. |
Line 516: | Line 516: | ||
Type gedit blog/templates/blog/blogs.html & [Enter] | Type gedit blog/templates/blog/blogs.html & [Enter] | ||
− | || | + | || Now, type''' gedit <space> blog slash templates slash blog slash blogs dot html <space> ampersand''' |
|- | |- | ||
|| [blogs.html] Type: | || [blogs.html] Type: | ||
Line 523: | Line 523: | ||
|| We are now in '''blogs.html'''. | || We are now in '''blogs.html'''. | ||
− | Before the '''body | + | Before the '''body closing tag''', add a link to the '''/logout url''' as shown here. |
|- | |- | ||
|| [blogs.html] | || [blogs.html] | ||
Line 560: | Line 560: | ||
|| Let us try to access the page '''get_blogs''' directly. | || Let us try to access the page '''get_blogs''' directly. | ||
− | In the address bar, type the '''URL '''as shown. | + | In the '''address bar''', type the '''URL '''as shown. |
− | As we have logged out, the authentication has failed. | + | As we have logged out, the '''authentication''' has failed. |
We have been redirected to the '''login''' page instead of '''get_blogs.''' | We have been redirected to the '''login''' page instead of '''get_blogs.''' | ||
|- | |- | ||
|| [browser] | || [browser] | ||
− | || Authentication will also fail, if we provide incorrect '''login''' details. | + | || '''Authentication''' will also fail, if we provide incorrect '''login''' details. |
|- | |- | ||
|| Switch to the terminal | || Switch to the terminal | ||
− | || This is how we create '''Django''' | + | || This is how we create '''Django authentication'''. |
Switch to '''terminal 2.''' | Switch to '''terminal 2.''' | ||
Line 589: | Line 589: | ||
|| In this tutorial, we have learnt to | || In this tutorial, we have learnt to | ||
− | * Create the '''login''' | + | * Create the '''login functionality''' |
− | * Use '''Django built-in login''' and '''logout functions''' | + | * Use '''Django's built-in login''' and '''logout functions''' |
|- | |- | ||
Line 596: | Line 596: | ||
|| As an assignment, | || As an assignment, | ||
− | * If an unauthenticated user tries to login, then redirect him/ her to the '''Login''' page. | + | * If an '''unauthenticated user''' tries to login, then redirect him/ her to the '''Login''' page. |
|- | |- |
Latest revision as of 16:12, 14 October 2019
Title of script: Django Authentication
Keywords: Video tutorial, Django Authentication
Visual cue | Narration |
Slide: Django Authentication | Hello and welcome to the spoken tutorial on “Django Authentication” |
Slide: Learning Objectives | In this tutorial, we will learn to:
|
Slide: System Requirements | To record this tutorial, I am using
|
Slide: Prerequisites | To follow this tutorial, you need to know
|
Slide: Django User Authentication | Django
|
Open a Terminal window
Press CTRl+ALT+T simultaneously |
Let us open the terminal by pressing Ctrl, Alt and T keys simultaneously on the keyboard. |
[Terminal]
cd my-django [Enter] |
Now using the cd command, go to the folder my hyphen django which we had created earlier. |
[Terminal] cd mysite and Press Enter | Then go to the mysite folder using the cd command.
Here onwards, please remember to press the Enter key after typing each command. |
[Terminal]
Type gedit blog/forms.py & [Enter] |
Let us now add a login form to the file forms.py located in the blog folder.
Type gedit <space> blog slash forms dot py <space> ampersand |
[forms.py]Type:
from django import forms from django.contrib.auth.forms import AuthenticationForm class LoginForm(AuthenticationForm): username = forms.CharField(label="Username", max_length=30, widget=forms.TextInput(attrs={'name': 'username'})) password = forms.CharField(label="Password", max_length=30, widget=forms.PasswordInput(attrs={'name': 'password'})) |
We are now in forms.py.
Next to the class ArticleForm, type the code as shown. Then let us import the AuthenticationForm. |
[forms.py] Highlight
class LoginForm |
Here we are specifying a custom form class. |
[forms.py] Highlight
AuthenticationForm |
Our LoginForm is inherited from AuthenticationForm. |
[forms.py] Highlight
from django.contrib.auth.forms import AuthenticationForm |
To do that, we need to import AuthenticationForm from django contrib auth forms module. |
[forms.py] Highlight
Username password |
Form fields username and password are declared here. |
[forms.py] Highlight
forms.CharField(label="Username", max_length=30) forms.CharField(label="Password", max_length=30) |
username and password are CharField.
CharFields are rendered as a text box on the web browser. |
[forms.py] Highlight
label="Username", max_length=30 |
Here, we pass two arguments label and max_length for the character field.
There are many other arguments available. Please refer to the Django documentation for the same. |
[forms.py] Highlight
widget=forms.TextInput(attrs={'name': 'username’}))’’’ ‘’’widget=forms.PasswordInput(attrs={'name': 'password'})) |
We have also passed an argument widget.
A widget is Django’s representation of an HTML element. |
Press Ctrl+S | Save the file. |
Only narration | We have now created the Login form.
Next, let us create a new template login.html to display the form. |
Switch to Terminal | Switch to the terminal |
[Terminal]
Type gedit blog/templates/blog/login.html & |
Type gedit <space> blog slash templates slash blog slash login dot html <space> ampersand |
[login.html] Type:
<html> <body> <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="login" /> </form> </body> </html> |
We are now in login.html
Type the code as shown here. |
[login.html]
Highlight ‘’’ {{ form.as_p }} |
form.as_p will render the form fields wrapped in p tag.
Here, we rendered the Login form from form dot py file using form.as_p |
Press Ctrl+S | We have now created the HTML template to display our form.
Save the file. |
Switch to Terminal | Switch to terminal. |
[Terminal]
Type gedit mysite/urls.py & [Enter] |
Let us now add the url for Login.
To do so, open the root URL file. Type gedit <space> mysite slash urls dot py <space> ampersand |
[mysite/urls.py] Type:
from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from blog.forms import LoginForm urlpatterns = [ path('admin/', admin.site.urls), path('blogs/', include('blog.urls', namespace='blog')), path('login/', auth_views.login, {'template_name': 'blog/login.html', 'authentication_form': LoginForm}, name='login'), ] |
We are now in root URL file which is under project mysite directory.
Modify the code as shown here.
|
[mysite/urls.py] Highlight
{'template_name':'blog/login.html',authentication_form': LoginForm} |
It renders a template login.html under the Blog App directory.
It also renders the authentication form which we created, which is LoginForm. |
[mysite/urls.py] Highlight
auth_views.login |
Django uses views to handle the login. |
[mysite/urls.py] Highlight
from django.contrib.auth import views as auth_views from blog.forms import LoginForm |
For that, we need to import two packages
|
Press Ctrl+S | We have now added the required URL for the login page.
Save the file. |
Switch to Terminal | Switch to terminal. |
[Terminal]
Type gedit mysite/settings.py & [Enter] |
Let us open settings.py file to configure the route.
Type gedit <space> mysite slash settings dot py <space> ampersand |
[settings.py] Type:
LOGIN_REDIRECT_URL = '/blogs/get_blogs/' |
We are now in settings.py file.
Scroll down to the bottom of the page. In the last line, type the code as shown. |
[settings.py] Highlight
LOGIN_REDIRECT_URL = '/blogs/get_blogs/' |
When the user is authenticated, this will redirect to get underscore blogs page. |
Press Ctrl+S | Save the file. |
Only narration | Now we need to apply the login_required decorator to all the view function. |
Switch to Terminal | Switch to terminal. |
[Terminal]
Type gedit blog/views.py & [Enter] |
Now, let us open the blog’s views.py file.
Type gedit <space> blog slash views dot py <space> ampersand |
[views.py] Highlight
@login_required(login_url="/login/") def index(request): return HttpResponse("Hello World")
def get_blogs(request): blogs = Blog.objects.all() context = {'blogs': blogs} return render(request, 'blog/blogs.html', context)
def add_blog(request, blog_id=None): if blog_id: blog = Blog.objects.get(id=blog_id) else: blog = Blog() |
We are now in views.py file.
Add the line at the rate login_required <within brackets> login_url equal to <within double quotes within slash> login above all the view function as shown. |
[views.py] Highlight
@login_required(login_url=”/login/”) |
View decorators can be used to restrict access to certainviews.
Django comes with somebuilt-in decorators, like login_required. If auser isauthenticated, login_required decorator successfully executes theview function. If not, it redirects theuser to thelogin URL. |
[views.py] Type:
from django.shortcuts import render from django.http import HttpResponse, HttpResponseNotFound from .models import Blog, Article from .forms import LoginForm from django.contrib.auth.decorators import login_required # Create your views here. |
In the import section, update the code as shown. |
[views.py] Highlight
from django.contrib.auth.decorators import login_required from .forms import LoginForm |
Here we have imported
login underscore required decorator from django.contrib.auth.decorator and LoginForm class from forms module. |
Press Ctrl+S | Save the file. |
Only narration | We have now created the login page and its redirection.
Let us verify this. |
Switch to Terminal | Switch to the terminal. |
[Terminal]
Press CTRL+SHIFT+T |
For our convenience, let us run the Django server in a separate terminal tab.
Press Shift, Ctrl and T keys simultaneously. |
[Terminal Tab 2] cd ..
Type source myapp_env/bin/activate and press Enter |
In the new tab, move to my-django directory using the cd command.
Activate the virtual environment. |
[Terminal tab 2] type cd mysite
Type python manage.py runserver [Enter] |
Now go to the mysite folder using cd command.
And run the server. |
Open a browser and type | Now, open a web browser.
In the address bar, type the URL as shown. Then press Enter. |
[browser] | Here, we can see a login page with the fields for username and password. |
[browser] | Let us provide our super user credentials, which we created earlier in this series. |
[browser] Type:
Username: root Password: sample123 |
I’m providing the details as follows:
Username as root and Password as sample123. |
[browser]
Click login |
Then, click on the login button. |
[browser]
Pointing to the browser’s address bar |
If the credentials are correct then we will be redirected to blogs/get_blogs page.
As we defined the Login Urls Redirect in settings.py file. |
[browser]
Pointing to the webpage Click OK |
The page with a pop-up “Welcome to the blog app!”appears.
Click on the OK button in the pop-up. |
Only narration | We have successfully created the login authentication system. |
Switch to mysite/urls.py | Next, let’s add a logout link to our page.
To do so, switch to the urls.py file in mysite folder. |
[mysite/urls.py] Type:
path('logout/', auth_views.logout, {'next_page': '/login'}, name='logout'), |
Add the line of code below login path as shown here. |
[mysite/urls.py]
Highlight auth_views.logout |
auth_views.logout is a Django authentication view to handle logout.
This will log out the user if logged in. Then it redirects to the log-in page. |
{'next_page': '/login'}, | next_page parameter determines the page to redirect after the user logs out.
|
[mysite/urls.py] Highlight
name='logout' |
We have set the URL pattern with the name, logout. |
Press Ctrl+S | Save the file. |
Switch to Terminal | Now, let us add the logout link to the blogs.html file.
Switch to terminal 1. |
[Terminal Tab 1]
Type gedit blog/templates/blog/blogs.html & [Enter] |
Now, type gedit <space> blog slash templates slash blog slash blogs dot html <space> ampersand |
[blogs.html] Type:
<p><a href="{% url 'logout' %}">Logout</a></p> |
We are now in blogs.html.
Before the body closing tag, add a link to the /logout url as shown here. |
[blogs.html]
Highlight {% url 'logout' %} |
Django URL Template tag gives the corresponding URL path for the URL name.
URL template tag uses the name given to the URL pattern in App URL file. |
Press Ctrl+S | We have now completed the logout authentication.
Save the file. |
Switch to Browser | Switch to browser and refresh the page. |
Click OK | Click on the OK button in the pop-up window. |
[browser]
(Pointing the web page) |
Here, we can see a link for Logout. |
[browser]
Click logout |
By clicking on the logout link, the page redirects us to the login page. |
[browser] Type | Let us try to access the page get_blogs directly.
In the address bar, type the URL as shown. As we have logged out, the authentication has failed. We have been redirected to the login page instead of get_blogs. |
[browser] | Authentication will also fail, if we provide incorrect login details. |
Switch to the terminal | This is how we create Django authentication.
Switch to terminal 2. |
Terminal] Press Ctrl+C keys
Type deactivate [Enter] |
Stop the server.
And deactivate the virtual environment. |
Switch to slide | With this, we come to the end of this tutorial.
Let us summarize. |
Slide: Summary | In this tutorial, we have learnt to
|
Slide: Assignment | As an assignment,
|
Slide: About Spoken Tutorial project | The video at the following link summarises the Spoken Tutorial project.
Please download and watch it. |
Slide: Spoken Tutorial workshops | The Spoken Tutorial Project team conducts workshops and gives certificates.
For more details, please write to us. |
Slide: Forum for specific questions: | Please post your timed queries in this Forum. |
Slide: FOSSEE to answer questions | Please post your general or technical questions in this Forum. |
Slide: Acknowledgement | Spoken Tutorial Project is funded by NMEICT, MHRD, Government of India.
More information on this mission is available at this link. |
Slide: Thanks Slide | This script has been contributed by Thiagarajar College of Engineering and the FOSSEE Project, IIT Bombay.
The video has been recorded by Praveen from Spoken Tutorial Project, IIT Bombay. Thanks for watching. |