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!

ИМ
  • Nov. 22, 2024, 11:51 a.m.

Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильный редирект. При переходе по ссылке /test/, меня редиректит на страницу авторизации(как и должно происходить в моем случае), после авторизации меня втупую перебрасывает на главную а не на предидущую страницу.

[22/Nov/2024 18:44:08] "GET /en/test/ HTTP/1.1" 302 0
[22/Nov/2024 18:44:08] "GET /accounts/login/?next=/en/test/ HTTP/1.1" 302 0
[22/Nov/2024 18:44:08] "GET /en/accounts/login/?next=/en/test/ HTTP/1.1" 200 11841
[22/Nov/2024 18:44:19] "POST /en/accounts/login/?next=/en/accounts/login/ HTTP/1.1" 302 0
[22/Nov/2024 18:44:19] "GET /en/accounts/login/ HTTP/1.1" 302 0
[22/Nov/2024 18:44:19] "GET / HTTP/1.1" 302 0
[22/Nov/2024 18:44:19] "GET /en/ HTTP/1.1" 200 10495

Comments

Only authorized users can post comments.
Please, Log in or Sign up
OI

C++ - Test 001. The first program and data types

  • Result:40points,
  • Rating points-8
AD

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

  • Result:50points,
  • Rating points-4
m

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

  • Result:80points,
  • Rating points4
Last comments
ИМ
Игорь МаксимовNov. 22, 2024, 10:51 p.m.
Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Evgenii Legotckoi
Evgenii LegotckoiNov. 1, 2024, 12:37 a.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 6:19 p.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 5:51 p.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 9:02 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Now discuss on the forum
Evgenii Legotckoi
Evgenii LegotckoiJune 25, 2024, 1:11 a.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 5:04 p.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 1:49 p.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…
9
9AnonimOct. 25, 2024, 7:10 p.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks