Django - Tutorial 017. Customize the login page to Django

авторизация, Django, login

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.
Support the author Donate

Comments

Only authorized users can post comments.
Please, Log in or Sign up
m
May 19, 2019, 1:49 a.m.
mahhaki

Qt - Test 001. Signals and slots

  • Result:78points,
  • Rating points2
S
May 17, 2019, 1:14 p.m.
SunBro

Qt - Test 001. Signals and slots

  • Result:42points,
  • Rating points-8
b
May 17, 2019, 4:18 a.m.
banana

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

  • Result:57points,
  • Rating points-2
Last comments
May 21, 2019, 8:10 p.m.
Дмитрий

Приветствую! Я думаю дойдёт и до этого, но пока изучать его у меня нет желания.
May 20, 2019, 7:20 p.m.
Евгений Легоцкой

Добрый день! Вы не думали разместить репозиторий проекта на GitHub?
P.
May 18, 2019, 2:03 p.m.
PELMYACH .

Спасибо большое! Вскоре буду разбираться!
May 18, 2019, 9:13 a.m.
Евгений Легоцкой

Добрый день! Отнимать значение общего счётчика можно в деструкторе класса кнопки QDynamicButton::~QDynamicButton(){ ResID--;} При этом я бы ещё переустанавливал значения вс...
P.
May 14, 2019, 10:33 p.m.
PELMYACH .

Здравствуйте!А не подскажите, как можно при удалении какой либо кнопки, у щётчика отнять значение?Дабы например четвёртой кнопке соответствовал ID 4, а не 5 скажем
Now discuss on the forum
May 24, 2019, 6:48 a.m.
Евгений Легоцкой

Если там будут только перечисления внутри namespace, то жа, достаточно будет заголовочного файла
May 24, 2019, 6:28 a.m.
Андрей Янкович

работает любой http сервер, и можно использовать обсалютно любой портпример <RemoteRepositories> <Repository> <Url>http://178.124.160.6:3030/A/B&l...;
May 23, 2019, 2:40 p.m.
Михаиллл

Попробовал сделать этот запрос по http и получил json файл. request.setUrl(QUrl("https://jsonplaceholder.typicode.com/todos/1")); Как Вы думаете, почему https не работает и как это и...
May 23, 2019, 10:42 a.m.
Михаиллл

Спасибо, помогло.
May 23, 2019, 6:31 a.m.
Евгений Легоцкой

Для задач и граф-то не нужен. Достаточно будет таблицы в локальной базе данных SQLite, в которой указывается задача, время и т.д. В этом разделе есть примеры по работа с базой д...

For registered users on the site there is a minimum amount of advertising

EVILEG
About
Services
Join us
© EVILEG 2015-2019
Recommend hosting TIMEWEB