Python-Django/C2/Django--Authentication/English

From Script | Spoken-Tutorial
Revision as of 15:36, 30 September 2019 by Pravin1389 (Talk | contribs)

Jump to: navigation, search
Django/C2/Django Authentication/English

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:
  • Create a login functionality
  • Use Django’s built-in login and logout functions
Slide: System Requirements To record this tutorial, I am using
  • Ubuntu Linux OS 16.04
  • Python 3.5
  • Python 3.4-venv or higher
  • gedit Text Editor and
  • Firefox web browser
Slide: Prerequisites To follow this tutorial, you need to know
  • How to create Templates and Forms in Django
  • If not, then please go through the prerequisite tutorials on this website.
Slide: Django User Authentication Django
  • provides an authentication and authorization system.
  • allows to verify the user credentials and
  • defines what actions each user is allowed to perform.
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 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 CharField.

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 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}

By default, 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
  • Django Authentication view from django.contrib.auth
  • And LoginForm from blog.forms module
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.

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")


@login_required(login_url="/login/")

def get_blogs(request):

blogs = Blog.objects.all()

context = {'blogs': blogs}

return render(request, 'blog/blogs.html', context)


@login_required(login_url="/login/")

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 @login_required(login_url="/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.

Update the code as shown.
[views.py] Highlight

from django.contrib.auth.decorators import login_required

from .forms import LoginForm

We have to import two packages.

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

http://localhost:8000/login

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_blog 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.


Here, next_page redirects to the login page.

[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]

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

http://localhost:8000/blogs/get_blogs/

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
  • Create the login functionality
  • Use Django built-in login and logout functions
Slide: Assignment As an assignment,
  • If an unauthenticated user tries to login, then redirect him/ her to the Login page.
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.

Contributors and Content Editors

Nancyvarkey, Pravin1389