How to create a form and authenticate Django user

1

Good night everyone.

I'm developing a project in django just for educational purposes and I could not find a solution to my problem.

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

I've already been able to generate a registration form, but I still have to authenticate the user.

What should I do?

Note: Django Version: 1.10.4

views.py

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', {})

models.py

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 those interested in viewing the project repository: GitHub

    
asked by anonymous 26.02.2017 / 04:01

1 answer

2

Use the "django authentication framework". Django brings a built-in authentication framework with authentication handlers, sessions, permissions and user groups. The authentication system already includes views for usual actions like 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 authentication framework includes the following models:

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

  • group: Group names for user categorization

  • permission: Autoexplicative

View to 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 url pattern for this view, in urls.py 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 needs to be created, the sample template I reproduce below extends a base (base.html). In the template 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 %}

Okay! Now, if you have not yet created the superuser, create it, run your project enter admin and create a user, then point the browser to your app login, something like link and you should see the template rendered with the login form.

Note: You can do a lot more, like for example a link to logout, reset of passwords, etc. The explanation here is an adaptation of examples from chapter 2 of the book: Django By Example.

    
01.03.2017 / 20:16