How to create a form and authenticate Django user

Asked

Viewed 4,680 times

1

Good night to you all.

I am developing a Django project for educational purposes only and I could not find a solution to my problem.

I could not generate a form for the user to log in and much less authenticate this user.

I already managed to generate a form for registration, but I still have to authenticate the user.

What should I do?

Note: Version of Django: 1.10.4

py views.

from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import CadastroForm

def index(request):

    return render(request, 'index.html')


def cadastro(request):

    if request.method == 'POST':
        form = CadastroForm(request.POST or None)

        if form.is_valid():
            return HttpResponseRedirect('/')

    else:
        form = CadastroForm()

    return render(request, 'cadastro.html', {'form': form})


def entrar(request):

    return render(request, 'entrar.html', {})

py.models

from django.db import models


# Create your models here.


class Cadastro(models.Model):

    name = models.CharField(max_length=100)
    email = models.EmailField(max_length=100)
    username = models.CharField(max_length=40)
    password = models.CharField(max_length=50)

Forms.py

from django import forms
from .models import Cadastro


class CadastroForm(forms.ModelForm):

    class Meta:
        model = Cadastro
        fields = ('name', 'email', 'username', 'password')
        widgets = {
            'password': forms.PasswordInput(),
        }

login.html

{% extends "base.html" %}

{% load widget_tweaks %}

{% block content %}

<div class="container" style="margin-top: 50px; width: 500px;">
  <h2 align="center">Login</h2>
  <form action="{% url 'blog:index' %}" method="post">
    {% csrf_token %}

    {% for field in form_login %}
    <div class="form-group">
      <label for="{{field.id_for_label}}">{{field.label}}</label>
        {{field|add_class:'form-control'}}
    </div>
    {% endfor %}
    <div class="submit" align="center" style="margin-bottom: 50px;">
      <button type="submit" class="btn btn-success">Enviar</button>
    </div>
  </form>
</div>


{% endblock %}

For anyone interested in seeing the project repository: Github

1 answer

2

Use "the Django Authentication framework". Django brings "built-in" a User framework with User handlers, sessions, permissions and user groups. The User System already includes views for usual actions such as login, logout, password change, etc. The package in which the system is contained is: Django.contrib.auth, by default it is included in your Settings when you make a startproject

The User Framework includes the following models:

  • User: Model for users with main fields: username, password, email, first_name, last_name and is_active.

  • group: Group names for user categorization

  • permission: Self-explanatory

View for the login

Our login view should trigger a login form, so let’s first create a new form in Forms.py

from django import forms
from django.contrib.auth.models import User

class LoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)

Now let’s create the view code itself:

from django.shortcuts import render
from django.http import HttpResponse
from django.contrib import messages
from django.contrib.auth import authenticate, login
from .forms import LoginForm

def user_login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            user = authenticate(username=cd['username'],
                   password=cd['password'])
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return HttpResponse('Authenticated',
                        successfully')
                else:
                    return HttpResponse('Disabled account')
            else:
                return HttpResponse('Invalid Login')
    else:
        form = LoginForm()
    return render(request, 'sua-app/login.html', {'form': form})

Now we need to create the Pattern url for this view, in.py urls within your application:

from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views

...
urlpaterns += [url(r'^login/$', auth_views.login, name='login'),]

The view can now be accessed by the URL, but the template for this view still remains to be created, the template example I play below extends a base (base.html). In the templates directory of your application create the login.html file:

{% extends "base.html" %}

{% block title %}Log-in{% endblock %}

{% block content %}
    <h1>Log-in</h1>
    <p>Use of formulário abaixo:</p>
    <form action="." method="post">
        {{ form.as_p }}
        {% csrf_token %}
        <p><input type="submit" value="Log-in"></p>
    </form>
{%  endblock %}

OK! Now, if you haven’t created superuser yet, create it, run your project in admin and create a user, then point the browser to the login of your app, something like http://127.0.0.1:8000/sua-app/login and Voce should see the template rendered with the login form.

Remark: You can do much more, such as a link to logout, password reset, etc. The explanation here is an adaptation of examples from chapter 2 of the book: Django By Example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.