Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting
TIMEWEB

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 .

Comments

Only authorized users can post comments.
Please, Log in or Sign up
v
Jan. 17, 2019, 11:51 a.m.
vitalir12

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

  • Result:20points,
  • Rating points-10
v
Jan. 17, 2019, 11:49 a.m.
vitalir12

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
v
Jan. 17, 2019, 11:13 a.m.
vitalir12

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

  • Result:28points,
  • Rating points-10
Last comments
I
Jan. 16, 2019, 8:06 a.m.
IscanderChe

Заработало. Забыл model->select(); вписать.
I
Jan. 16, 2019, 8:02 a.m.
IscanderChe

Всё равно пусто, хотя строка с данными в базу добавляется.
Jan. 16, 2019, 7:51 a.m.
Евгений Легоцкой

потому, что нужно сохранять информацию для всех остальных ролей и столбцов через вызов переопределённого метода. Да к тому же вы ещё и зациклили вызов метода data. QVariant MySqlTableModel:...
I
Jan. 16, 2019, 7:43 a.m.
IscanderChe

Сделал вот так. В tableView ничего нет, кроме заголовка. QVariant MySqlTableModel::data(const QModelIndex &index, int role) const{ if (role == Qt::DisplayRole) { QTime ...
Now discuss on the forum
Jan. 18, 2019, 11:26 a.m.
nayk1982

Для Desktop делал так: void pause(int ms){ QTimer timer; timer.setInterval( qBound(1, ms, 3600000) ); timer.setSingleShot(true); QEventLoop loop; QObject::connect(&...
Jan. 17, 2019, 12:01 p.m.
Алексей Внуков

у меня просто есть отдельное поле с чекбоксамими какие колонки нужно отображать CheckBox { id: checkBox text: qsTr("some text") checked: true onC...
Jan. 15, 2019, 4:53 p.m.
Михаиллл

Спасибо, заработало.Но выдало обычный текст без форатирования HTML.Придется искать дальше
Jan. 15, 2019, 12:52 p.m.
BlinCT

Я же вам выше написал CLion умеет работать с ремоут машинами. И Qt так же собирает.
Join us in social networks

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