Evgenii Legotckoi
Evgenii LegotckoiJan. 7, 2017, 8:20 a.m.

Django - Tutorial 017. Customize the login page to Django

In order to make the registration of the login page in the same style with the design throughout the site, you can prepare a design template and replace the url pattern to give us an view of the desired page with the desired pattern. It may also be useful for the introduction of functional locks from password guessing and more intelligent redirect the user to a page of the site after login, depending on whether the user has a status of staff or not.

To work with the user authorization propose to use a separate application/module that will be called accounts .

Authorization Form is not required to write, because you can use the standard form AuthenticationForm , you will need to use in the login page template.

accounts module structure

accounts/
    templates/
        accounts/
            login.html
            login_widget.html
    __init__.py
    admin.py
    apps.py
    models.py
    special_func.py
    urls.py
    views.py

This module uses two templates:

  • login.html - a template for the login page
  • login_widget.html - a template for login widget that can be placed on any page of the site, the user can log in, not only from the login page, but also from any page with the article, for example.

special_func.py file contains some useful features, such as the receipt of the previous Url from request to redirect the user back to the page where the user is logged in.


login_widget.html

I remind you that I use django_bootstrap3 on the site, so the template will be using it.

<form id="contact_form" action="{% url 'accounts:login' %}" method="post">
    {% load bootstrap3 %}
    {% csrf_token %}
    {% bootstrap_form login_form %}
    {% buttons %}
        <div class="form-group">
            <button type="submit" class="btn btn-primary">Login</button>
        </div>
    {% endbuttons %}
</form>

login.html

The template is added to the login widget. By the same principle, you can add the widget to any login page anywhere in the site.

{% extends 'home/base.html' %}
{% block content %}
    <div class="col-md-offset-3 col-md-6 voffset-60">
        <h1>Login to site</h1>
        {% include 'accounts/login_widget.html' %}
    </div>
{% endblock %}

urls.py files

To replace the login page, and in general authorization to use the widget, you must add the following url patterns to urls.py of your project.

from django.conf.urls import url, include
from django.contrib import admin

from accounts.views import ELoginView    # View of autorization of accounts module

# To intercept the login page, you must set the path to this page
# befor url to admin panel and specify the view 
# that will now handle authentication
urlpatterns = [
    url(r'^admin/login/', ELoginView.as_view()),    
    url(r'^admin/', admin.site.urls),
    url(r'^accounts/', include('accounts.urls')),    # also add url authorization module
]

urls.py accounts module file will look as follows:

# -*- coding: utf-8 -*-
from django.conf.urls import url

from . import views

app_name = 'accounts'
urlpatterns = [
    url(r'^login/$', views.ELoginView.as_view(), name='login'),
]

settings.py и apps.py

Do not forget to register the authorization module in the site settings.

apps.py

from django.apps import AppConfig


class AccountsConfig(AppConfig):
    name = 'accounts'

settings.py

INSTALLED_APPS = [
    'accounts.apps.AccountsConfig',
]

views.py

And now for the view, which will process the authorization as from the login page and another page with lyuoy.

# -*- coding: utf-8 -*-
from urllib.parse import urlparse

from django.shortcuts import redirect, render_to_response
from django.contrib import auth
from django.template.context_processors import csrf
from django.views import View
from django.contrib.auth.forms import AuthenticationForm
from .special_func import get_next_url

class ELoginView(View):

    def get(self, request):
        # if the user is logged in, then do a redirect to the home page
        if auth.get_user(request).is_authenticated:
            return redirect('/')
        else:
            # Otherwise, form a context with the authorization form 
            # and we return to this page context.
            # It works, for url - /admin/login/ and for /accounts/login/ 
            context = create_context_username_csrf(request)
            return render_to_response('accounts/login.html', context=context)

    def post(self, request):
        # having received the authorization request
        form = AuthenticationForm(request, data=request.POST)

        # check the correct form, that there is a user and he entered the correct password
        if form.is_valid():
            # if successful authorizing user
            auth.login(request, form.get_user())
            # get previous url
            next = urlparse(get_next_url(request)).path
            # and if the user of the number of staff and went through url /admin/login/
            # then redirect the user to the admin panel
            if next == '/admin/login/' and request.user.is_staff:
                return redirect('/admin/')
            # otherwise do a redirect to the previous page,
            # in the case of a / accounts / login / will happen is another redirect to the home page
            # in the case of any other url, will return the user to the url
            return redirect(next)

        # If not true, then the user will appear on the login page
        # and see an error message
        context = create_context_username_csrf(request)
        context['login_form'] = form

        return render_to_response('accounts/login.html', context=context)


# helper method to generate a context csrf_token
# and adding a login form in this context
def create_context_username_csrf(request):
    context = {}
    context.update(csrf(request))
    context['login_form'] = AuthenticationForm
    return context

For Django I recommend VDS-server of Timeweb hoster .

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
г
  • ги
  • April 24, 2024, 3:51 a.m.

C++ - Test 005. Structures and Classes

  • Result:41points,
  • Rating points-8
l
  • laei
  • April 23, 2024, 9:19 p.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:10points,
  • Rating points-10
l
  • laei
  • April 23, 2024, 9:17 p.m.

C++ - Тест 003. Условия и циклы

  • Result:50points,
  • Rating points-4
Last comments
k
kmssrFeb. 9, 2024, 7:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 11:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 9:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 10:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
G
GarApril 22, 2024, 5:46 p.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 7:45 p.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 6:41 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 2:35 p.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 4:47 p.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks