0

Django: Simple User Authentication Login and Logout. This problem hasbeen asked with someone in in https://www.facebook.com/groups/DjangoID/, he asked “how to custom template of login form in django”.

First, makesure you understrand how django is work. and in this method, we used default model User from django. and default user authentications from django. There just modified template for login page.

There we use Django1.8++

1. In your views.py, create some function for viewing user authentications with some conditions.

from django.contrib.auth import logout
from django.shortcuts import redirect

class User_Authentication_Views(object):
    #def registration_view(self, request):
    #    #do_stuff with form and save into your model or whatever you need.

    def logout_view(self, request):
        logout(request)
        return redirect('/login/')

2. In your urls.py, customing default django.contrib.auth.views.login with your template.

from django.conf.urls import include, url
from . import views

urlpatterns = [
    #url user authentication
    url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'login_form.html'}, name='login_page'),
    url(r'^logout/$', views.User_Authentication_Views().logout_view, name='logout_page'),
]

3. In your templates/login_form.html, you can call your form with {{ form.as_p }}{{ form.as_table }}, or if you need to specific egg like this: {{ form.username }} and {{ form.password }} –> it just showing egg: <input type="text" name="username" id="id_username" />, please checkout in this docs for more: https://docs.djangoproject.com/en/1.9/topics/forms/

{% extends 'base.html' %}<!-- this just example if you wan't extending from base.html -->
{% block content %}<!-- blocking content from base.html -->
<div class="panel">
    <div class="panel-body">
    {% if form.errors %}
        <p class="alert alert-danger">
           Upps, Username and Password didn't match!
        </p>
    {% endif %}

    <form action="." method="POST">{% csrf_token %}
        {{ form.as_p }}
      <button type="submit" class="btn btn-success"></button>
      <input type="hidden" name="next" value="/" />
    </form>
    </div>
</div>
{% endblock %}

Docs: https://docs.djangoproject.com/en/1.9/topics/auth/default/#using-the-django-authentication-system

Hope it usefull..

python django templates

Your Answer

blog comments powered by Disqus