D
D
Daniel2019-12-23 11:54:39
Django
Daniel, 2019-12-23 11:54:39

How to implement authorization in Django?

Dobre, fellow programmers and people looking for a solution to the problem.
I have implemented django registration and authorization, but the trouble is that I can't check if I'm logged in.
In django, I'm completely green, don't throw sticks too hard.
views.py

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

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 redirect('/')
                else:
                    return HttpResponse('Disabled account')
            else:
                return HttpResponse('Invalid login')
    else:
        form = LoginForm()
    return render(request, 'login/account_login.html', {'form': form})

forms.py
from django import forms


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

html
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <h1>Вход на сайт</h1>
    {% if error %}
        <div style="color:red;">{{ error }}</div>
    {% endif %}
     <form method="post" action="" class="login">
         {% csrf_token %}
    <p>
      <label for="login">Логин:</label>
      <input type="text" name="login" id="login" >
    </p>

    <p>
      <label for="password">Пароль:</label>
      <input type="password" name="password" id="password" >
    </p>

    <p class="login-submit">
      <button type="submit" class="login-button">Войти</button>
    </p>

  </form>
</body>
</html>

There may be errors in the code, but I have been racking my brains on this project for a very long time, any criticism is welcome.
Upd: When you enter a password and login, the page is updated and that's it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2019-12-23
@9DirtyDaniel9

I implemented django registration and authorization, but the trouble is that I don't check if I'm logged in.

What is the problem to check, is it difficult to read the documentation? https://docs.djangoproject.com/en/3.0/topics/auth/...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question