Authentication system in the forum application #1: Make a change password template and Implement the change password feature

in utopian-io •  5 years ago 

Repository

https://github.com/python

What Will I Learn?

  • Make a change password template
  • Implement the change password feature

Requirements

  • Basic Python
  • Install Python 3
  • Install Django

Resources

Difficulty

Basic

Tutorial Content

Hi everyone, in my previous tutorial, I discussed discussing creating a forum application with Django. In this tutorial, actually has something to do with the tutorial series. but I will separate this tutorial because this tutorial will discuss the authentication system in detail and implement it directly on the real project. In the forum application tutorial we have created a login system but what we are using is a system that has been provided by Django. In this tutorial, we will start the real authentication for the web application that we created. This tutorial will relate to the forum application that we have made before so I suggest you follow the tutorial first.

Change Password

In this section, we will add a new feature that will complete the authentication system of our forum application, namely the change password feature. Before we make the feature, it's good we can see that auth has been installed in Django as we can see in the picture below:

  • Preparation

Screenshot_3.png

we have installed 'django.contrib.auth''django.contrib.auth' automatically from Django. to determine whether the application has been installed we can run migrate. migrate is used to apply all modules that have been installed in Django. we can do it like the following:

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

  • Create view change password

After making preparations we will start making the change password feature. actually by using django.auth we already have a password change page like the picture below:

Screenshot_4.png

we can see in the picture above that we have provided a field that we need to change our account password. but the view is the default view of Django.auth, we can replace it with our own style. to overwrite the default view we start by making the URL like the example below:

accounts/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('signup/', views.SignUp.as_view(), name='signup'),
    path('password_change/', views.ChangePassword, name='change-password') // define path
]
  • Previously at accounts/urls.py, we already have a signup/ URL to do a signup and here we will add a new URL which is 'password_change/'.

  • In the URL 'password_changes /' we will use the ChangePassword class and we can add alias name 'change-password', so we can easy to call this URL.

Now that we have created the URL and defined the ChangePassword class, now we will create the function in accounts/views.py.

  • Create ChangePassword class

We will start making the ChangePassword() function, in this function we will receive a request from the user, the request that we will use to retrieve POST data by the User. For more details, we can see the code below:

accounts/views.py

from django.shortcuts import render
from django.urls import reverse_lazy
from django.views import generic
// Django contrib
from django.contrib.auth.forms import UserCreationForm, PasswordChangeForm
from django.contrib.auth import update_session_auth_hash

class SignUp(generic.CreateView):
    form_class = UserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'signup.html'

def ChangePassword(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)
    else: // if user not submit
        form = PasswordChangeForm(request.user)
    return render(request, 'change_password.html', {'form' : form})

If the user submits on the form if request.method == 'POST':

  • In the code, above we can see that we have a SignUp() class. In the ChangePassword() function we will receive a request from the user.

  • We will create a form that is used to input new passwords. Because in the form we will receive data using the POST method so we will check it like the following if request.method == 'POST'. So we will only perform the function below if we have submitted the form.

  • Django has provided a form to change the password, we can use this by importing it first like from django.contrib.auth.forms import UserCreationForm, PasswordChangeForm.

  • Now, all we need is to pass the data that is in the POST request request.POST into the PasswordChangeForm(request.POST) function and then we can check whether the data on the form is valid in this way if form.is_valid():.

  • If the form is valid then we will save the data on the form like this user = form.save() and the thing to note is how we will refresh the session when the user's password has been changed. Because we have logged in with a new password. We can use function update_session_auth_hash provided by django.contrib.auth. to use it we must import it first like this from django.contrib.auth import update_session_auth_hash

  • to use the update_session_auth_hash(request, user) function we need two parameters. The first parameter is a request from the user request and the second is the new data that has been stored user from user = form.save().


    If user not submit else:

  • If the user does not submit in the form then we will render our change password template. I will create a template named change_password.html, this template is a template that we can set ourselves not from Django.

  • We will render the template and pass the form as follows return render(request, 'change_password.html', {'form' : form}). the 'form' is the key and the form is value from form = PasswordChangeForm(request.user).

  • Create template change_password

We have defined the template that we will render, namely change_password.html, now in this section we will create the template. We will create the template in the account/ templates directory. For more details, you can see the structure of the project as shown below:

Screenshot_1.png

We can see in the picture above our template name is change_password.html now we will make the template like this:

account/templates/change_password.html

{% extends "base.html" %}

{% block title %} Change Password{% endblock %}

{% block content %}
<h2>Change your password</h2>
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" name="button">Submit</button>
</form>

{% endblock%}
  • We can render the form like this {{form.as_p}}. form comes from the key that we oper when rendering the change_template template.

Screenshot_2.png

If it's finished making the template eat we can run our project using python manage.py runserver. If there is no error then we can see the results as shown below:

ezgif.com-video-to-gif.gif

Implement change password

Now we will implement our change password feature, but before that, I will add a redirect when the user successfully changes the password like this:

account/views.py

def ChangePassword(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)
            return redirect(reverse('home')) // redirect to home
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'change_password.html', {'form' : form})
  • I will redirect to the homepage page when the user successfully changes the password, to use the redirect I will import reverse first from django.urls import reverse. After importing it we can use it as follows: return redirect (reverse ('home')). home is the alias of our homepage. We will do a demonstration like the one below, so I have an account like follows:

Username: milleaduski1994
OLD password: newadmin1994
New password: admin1994

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

We can see in the picture above we managed to implement the change password feature according to our own needs. thank you for following this tutorial, hopefully, it's useful for you

Curriculum

  • Forum app

django#1, django#2, django#3, django#4, django#5, django#6, django#7, django#8, django#8, django#9, django#10, django#11

Proof of work done

https://github.com/milleaduski/forums-django

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

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

  • Tutorial well explained and detailed, but it would be nice to improve the structure of the contribution a bit more.

  • We suggest you enter a shorter title in your tutorial. Put the key words of what you will explain in the contribution.

  • Use shorter paragraphs and give breaks between them. It will make it easier to read your tutorial.

  • With this feature you could have also developed the password recovery functionality in the login system. With a confirmation email sending of the password change request.

Thank you for your work in developing this tutorial.
Looking forward to your upcoming tutorials.

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? 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!