Skip to content

Login

In this video, we are going to learn how to implement the feature of login in django.

Resources:

Form

At first, we need to create a login form in the forms.py file.

In the forms.py file of user, import the AuthenticationForm.

from django.contrib.auth.forms import (UserCreationForm, AuthenticationForm)

Now, create a class named LoginForm and inherit the AuthenticationForm.

class LoginForm(AuthenticationForm):

Now, we need to add form-control to every field of the Login Form.

    def __init__(self, *args, **kwargs):
        super(LoginForm, self).__init__(*args, **kwargs)
        for visible in self.visible_fields():
            visible.field.widget.attrs["class"] = "form-control"

Create a meta class to link this form to our user model.

    class Meta:
        model = User
        fields = "__all__"

Views

After creating the form, import it in the views.py file.

from user.forms import SignupForm, LoginForm

Now, create a login view.

[At first, explain the get request and then post request.]

def login(request):
    # When the user sends the post request.
    if request.method == "POST":
        # At first, instantiate the Login Form
        form = LoginForm(request, request.POST)
        # Then check whether the form is valid or not
        if form.is_valid():
            # If the form is valid, extract the email and password from the form data.
            email = form.cleaned_data["username"]
            password = form.cleaned_data["password"]
            # Now, we need to authenticate this email and password.
            # Django provies a method named authentication. Import it [Code written below]
            # If the email and password is correct, authenticate returns a user object.
            user = authenticate(email=email, password=password)
            # If the credentials are not valid, it will return None.
            # So, we need to check whether this user is None or not
            # If the user is not None:
            if user is not None:
                # Then we need to perform login for this user.
                # Actually, Django provides a method named login which can be imported from contrib.auth [Code Below]
                # This method perform user login using session based authentication approach.
                user_login(request, user)
                # Once the user is logged in to the session, we will display a success message.
                messages.success(request, "Logged in Successfully")
                # After that redirect the user to the index page.
                return HttpResponseRedirect(reverse("index"))
            # But if the user is none then it means that credentials were invalid.
            # So, we will show an error message.
            messages.error(request, "Please Enter Correct Username and Password")
            # Redirect the user to the login page.
            return HttpResponseRedirect(reverse("accounts:login"))
        # If the form was invalid that means, if user enters invalid data then show an error message.
        messages.error(request, "Invalid Login! Please enter correct data")
        # And render the login.html file to the user to resubmit the login form.
        return render(request, "user/login.html", {"form": form})
    # If the user sends the get request, we will show the login form.
    context = {
        "form": LoginForm,
    }
    # We will render this loginform in the login.html file.
    return render(request, "user/login.html", context)
from django.contrib.auth import (authenticate, login as user_login)

In this way, we have created the login view.

Templates

Now, lets add the template for this view.

Create a login.html file in the templates folder.

I have attached login.html file in the resources section. Download it and copy its content and paste it in the html file.

{% extends 'mysite/base.html' %}

{% block title %} 
    <title>Login</title>
{% endblock %}

{% block content %}
<div class="card p-3">
   <div class="card-body">
      <h4>Enter your email and password to login</h4>
      {% include "components/form.html" with form_name="Login" %}
   </div>
   <p class="p-3">
      <a href="#">Reset Password</a>
   </p>
</div>
{% endblock content %}

URLS

At last, add a url for the login view.

path("login/", views.login, name="login"),

[Run the development server and see the changes.]