In this post we'll implement a view using the Django authentication framework to allow users to log in to our website. Our view should perform the following actions to log in a user:
1. Get the username and password by posting a form
2. Authenticate the user against the data stored in the database
3. Check whether the user is active
4. Log the user into the website and start an authenticated session
The first step will be to create a login form. The code for this form is shown below:
from django import forms
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
Save this file as forms.py file in your account application directory. This form will be used to authenticate users against the database. We use the PasswordInput widget to render its HTML input
element, including a type="password" attribute, so that the browser treats it as a password input.
The second step is to edit the views.py file of your account application and add the following code to it:
from django.http import HttpResponse
from django.shortcuts import render
from django.contrib.auth import authenticate, login
from .forms import LoginForm
# Create your views here.
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(request,
username=cd['username'],
password=cd['password'])
if user is not None:
if user.is_active:
login(request,user)
return HttpResponse('Authenticated successfully')
else:
return HttpResponse('Disabled account')
else:
return response('Invalid login')
else:
form = LoginForm()
return render(request,'account/login.html',{'form':form})
This is our basic login view. When the user submits the form via POST, we perform the following actions:
LoginForm() to display it in the template.
The third step is to create a URL pattern for this view. See the following code:
from django.urls import path
from . import views
urlpatterns = [
#post views
path('login/', views.user_login, name='login'),
]
Save this file as urls.py file in your account application directory.
The fourth step is to edit the main urls.py file located in your bookmarks project directory, import include, and add the URL patterns of the account application, as shown in the following code:
path('account/', include('account.urls')
The complete file will be as follows:
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('account/', include('account.urls'),
]
After we finish this step our login view can be accessed by a URL.
In the fifth step we'll create a template for this view. Start by creating a base template that can be extended by the login template. Create the following files and directories inside the account application directory:
templates/
account/
login.html
base.html
Now edit the base.html file and add the following code to it:
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link href="{% static "css/base.css" %}" rel="stylesheet">
</head>
<body>
<div id="header">
<span class="logo">Bookmarks</span>
</div>
<div id="content">
{% block content %}
{% endblock %}
</div>
</body>
</html>
This will be the base template for the website.We include the CSS styles in the main template. Create static/directory in the account application and copy the required CSS files into it.
The base template defines a title block and a content block that can be filled with content by the templates that extend from it. Let's fill in the template for our login form. See the code below:
{% extends "base.html" %}
{% block title %}Log-in{% endblock %}
{% block content %}
<h1>Login</h1>
<p> Please use the following form to log-in:</p>
<form action="." method="post">
{{form.as_p}}
{% csrf_token %}
<p><input type="submit" value="Log in" ></p>
</form>
{% endblock %}
Save this file at C:\bookmarks\account\templates\account as login.html. This template includes the form that is instantiated in the view. Since our form will be submitted via POST, we will include the {% csrf_token %} template tag for CSRF protection.
At the moment there are no users in our database as we didn't create any, so we need to create a superuser first in order to be able to access the administration site to manage other users. Open the command line and execute python manage.py createsuperuser. Fill in the desired username, email, and password. Yout command window should look like:
(bm_env) C:\bookmarks>python manage.py createsuperuser
Username (leave blank to use 'python'): admin
Email address:
Password:
Password (again):
Superuser created successfully.
(bm_env) C:\bookmarks>
Now run the development server using the python manage.py runserver command and open http://127.0.0.1:8000/admin/ in your browser. Access the administration site using the credentials of the user you just created. You will see the Django administration site, including the User and Group models of the Django authentication framework as shown below:
Now we create a new user using the administration site, I have created vivek as user:
Now open http://127.0.0.1:8000/account/login/ in your browser, you should see the rendered template, including the login form as shown below :
If you enter valid credentials, you will get an Authenticated successfully message, like this:
If you enter a non-existing user or a wrong password, you will get an Invalid login message:
The login view we have created is a good exercise to understand the process of user authentication in Django. However, we can use the default Django authentication views in most cases. In the next post we'll see how to use the default Django authentication views.
1. Get the username and password by posting a form
2. Authenticate the user against the data stored in the database
3. Check whether the user is active
4. Log the user into the website and start an authenticated session
The first step will be to create a login form. The code for this form is shown below:
from django import forms
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
Save this file as forms.py file in your account application directory. This form will be used to authenticate users against the database. We use the PasswordInput widget to render its HTML input
element, including a type="password" attribute, so that the browser treats it as a password input.
The second step is to edit the views.py file of your account application and add the following code to it:
from django.http import HttpResponse
from django.shortcuts import render
from django.contrib.auth import authenticate, login
from .forms import LoginForm
# Create your views here.
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(request,
username=cd['username'],
password=cd['password'])
if user is not None:
if user.is_active:
login(request,user)
return HttpResponse('Authenticated successfully')
else:
return HttpResponse('Disabled account')
else:
return response('Invalid login')
else:
form = LoginForm()
return render(request,'account/login.html',{'form':form})
This is our basic login view. When the user submits the form via POST, we perform the following actions:
- Instantiate the form with the submitted data with form =LoginForm(request.POST).
- Check whether the form is valid with form.is_valid(). If it is not valid, we display the form errors in our template (for example, if the user didn't fill in one of the fields).
- If the submitted data is valid, we authenticate the user against the database using the authenticate() method. This method takes the request object, the username, and the password parameters and returns the User object if the user has been successfully authenticated, or None otherwise. If the user has not been authenticated, we return a raw HttpResponse, displaying the Invalid login message.
- If the user was successfully authenticated, we check whether the user is active, accessing its is_active attribute. This is an attribute of Django's user model. If the user is not active, we return an HttpResponse that displays the Disabled account message.
- If the user is active, we log the user into the website. We set the user in the session by calling the login() method and return the Authenticated successfully message.
LoginForm() to display it in the template.
The third step is to create a URL pattern for this view. See the following code:
from django.urls import path
from . import views
urlpatterns = [
#post views
path('login/', views.user_login, name='login'),
]
Save this file as urls.py file in your account application directory.
The fourth step is to edit the main urls.py file located in your bookmarks project directory, import include, and add the URL patterns of the account application, as shown in the following code:
path('account/', include('account.urls')
The complete file will be as follows:
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('account/', include('account.urls'),
]
After we finish this step our login view can be accessed by a URL.
In the fifth step we'll create a template for this view. Start by creating a base template that can be extended by the login template. Create the following files and directories inside the account application directory:
templates/
account/
login.html
base.html
Now edit the base.html file and add the following code to it:
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link href="{% static "css/base.css" %}" rel="stylesheet">
</head>
<body>
<div id="header">
<span class="logo">Bookmarks</span>
</div>
<div id="content">
{% block content %}
{% endblock %}
</div>
</body>
</html>
This will be the base template for the website.We include the CSS styles in the main template. Create static/directory in the account application and copy the required CSS files into it.
The base template defines a title block and a content block that can be filled with content by the templates that extend from it. Let's fill in the template for our login form. See the code below:
{% extends "base.html" %}
{% block title %}Log-in{% endblock %}
{% block content %}
<h1>Login</h1>
<p> Please use the following form to log-in:</p>
<form action="." method="post">
{{form.as_p}}
{% csrf_token %}
<p><input type="submit" value="Log in" ></p>
</form>
{% endblock %}
Save this file at C:\bookmarks\account\templates\account as login.html. This template includes the form that is instantiated in the view. Since our form will be submitted via POST, we will include the {% csrf_token %} template tag for CSRF protection.
At the moment there are no users in our database as we didn't create any, so we need to create a superuser first in order to be able to access the administration site to manage other users. Open the command line and execute python manage.py createsuperuser. Fill in the desired username, email, and password. Yout command window should look like:
(bm_env) C:\bookmarks>python manage.py createsuperuser
Username (leave blank to use 'python'): admin
Email address:
Password:
Password (again):
Superuser created successfully.
(bm_env) C:\bookmarks>
Now run the development server using the python manage.py runserver command and open http://127.0.0.1:8000/admin/ in your browser. Access the administration site using the credentials of the user you just created. You will see the Django administration site, including the User and Group models of the Django authentication framework as shown below:
Now we create a new user using the administration site, I have created vivek as user:
Now open http://127.0.0.1:8000/account/login/ in your browser, you should see the rendered template, including the login form as shown below :
If you enter valid credentials, you will get an Authenticated successfully message, like this:
If you enter a non-existing user or a wrong password, you will get an Invalid login message:
The login view we have created is a good exercise to understand the process of user authentication in Django. However, we can use the default Django authentication views in most cases. In the next post we'll see how to use the default Django authentication views.
0 comments:
Post a Comment