Evgenii Legotckoi
Jan. 7, 2017, 7:20 p.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

  1. accounts/
  2. templates/
  3. accounts/
  4. login.html
  5. login_widget.html
  6. __init__.py
  7. admin.py
  8. apps.py
  9. models.py
  10. special_func.py
  11. urls.py
  12. 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.

  1. <form id="contact_form" action="{% url 'accounts:login' %}" method="post">
  2. {% load bootstrap3 %}
  3. {% csrf_token %}
  4. {% bootstrap_form login_form %}
  5. {% buttons %}
  6. <div class="form-group">
  7. <button type="submit" class="btn btn-primary">Login</button>
  8. </div>
  9. {% endbuttons %}
  10. </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.

  1. {% extends 'home/base.html' %}
  2. {% block content %}
  3. <div class="col-md-offset-3 col-md-6 voffset-60">
  4. <h1>Login to site</h1>
  5. {% include 'accounts/login_widget.html' %}
  6. </div>
  7. {% 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.

  1. from django.conf.urls import url, include
  2. from django.contrib import admin
  3.  
  4. from accounts.views import ELoginView # View of autorization of accounts module
  5.  
  6. # To intercept the login page, you must set the path to this page
  7. # befor url to admin panel and specify the view
  8. # that will now handle authentication
  9. urlpatterns = [
  10. url(r'^admin/login/', ELoginView.as_view()),
  11. url(r'^admin/', admin.site.urls),
  12. url(r'^accounts/', include('accounts.urls')), # also add url authorization module
  13. ]

urls.py accounts module file will look as follows:

  1. # -*- coding: utf-8 -*-
  2. from django.conf.urls import url
  3.  
  4. from . import views
  5.  
  6. app_name = 'accounts'
  7. urlpatterns = [
  8. url(r'^login/$', views.ELoginView.as_view(), name='login'),
  9. ]

settings.py и apps.py

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

apps.py

  1. from django.apps import AppConfig
  2.  
  3.  
  4. class AccountsConfig(AppConfig):
  5. name = 'accounts'

settings.py

  1. INSTALLED_APPS = [
  2. 'accounts.apps.AccountsConfig',
  3. ]

views.py

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

  1. # -*- coding: utf-8 -*-
  2. from urllib.parse import urlparse
  3.  
  4. from django.shortcuts import redirect, render_to_response
  5. from django.contrib import auth
  6. from django.template.context_processors import csrf
  7. from django.views import View
  8. from django.contrib.auth.forms import AuthenticationForm
  9. from .special_func import get_next_url
  10.  
  11. class ELoginView(View):
  12.  
  13. def get(self, request):
  14.   # if the user is logged in, then do a redirect to the home page
  15. if auth.get_user(request).is_authenticated:
  16. return redirect('/')
  17. else:
  18.   # Otherwise, form a context with the authorization form
  19.   # and we return to this page context.
  20.   # It works, for url - /admin/login/ and for /accounts/login/
  21. context = create_context_username_csrf(request)
  22. return render_to_response('accounts/login.html', context=context)
  23.  
  24. def post(self, request):
  25.   # having received the authorization request
  26. form = AuthenticationForm(request, data=request.POST)
  27.  
  28.   # check the correct form, that there is a user and he entered the correct password
  29. if form.is_valid():
  30.   # if successful authorizing user
  31. auth.login(request, form.get_user())
  32.   # get previous url
  33. next = urlparse(get_next_url(request)).path
  34.   # and if the user of the number of staff and went through url /admin/login/
  35.   # then redirect the user to the admin panel
  36. if next == '/admin/login/' and request.user.is_staff:
  37. return redirect('/admin/')
  38.   # otherwise do a redirect to the previous page,
  39.   # in the case of a / accounts / login / will happen is another redirect to the home page
  40.   # in the case of any other url, will return the user to the url
  41. return redirect(next)
  42.  
  43.   # If not true, then the user will appear on the login page
  44.   # and see an error message
  45. context = create_context_username_csrf(request)
  46. context['login_form'] = form
  47.  
  48. return render_to_response('accounts/login.html', context=context)
  49.  
  50.  
  51. # helper method to generate a context csrf_token
  52. # and adding a login form in this context
  53. def create_context_username_csrf(request):
  54. context = {}
  55. context.update(csrf(request))
  56. context['login_form'] = AuthenticationForm
  57. return context

For Django I recommend VDS-server of Timeweb hoster .

Do you like it? Share on social networks!

ИМ
  • Nov. 22, 2024, 9:51 p.m.

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

  1. [22/Nov/2024 18:44:08] "GET /en/test/ HTTP/1.1" 302 0
  2. [22/Nov/2024 18:44:08] "GET /accounts/login/?next=/en/test/ HTTP/1.1" 302 0
  3. [22/Nov/2024 18:44:08] "GET /en/accounts/login/?next=/en/test/ HTTP/1.1" 200 11841
  4. [22/Nov/2024 18:44:19] "POST /en/accounts/login/?next=/en/accounts/login/ HTTP/1.1" 302 0
  5. [22/Nov/2024 18:44:19] "GET /en/accounts/login/ HTTP/1.1" 302 0
  6. [22/Nov/2024 18:44:19] "GET / HTTP/1.1" 302 0
  7. [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
  • Last comments
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup