Django Пользовательская форма входа пользователя не работает - PullRequest
0 голосов
/ 27 апреля 2020

Я новичок в Django, и я создал пользовательскую модель (Person), используя AbstractBaseUser и пользовательские формы для регистрации (RegForm) и входа в систему (LogForm). С RegForm все в порядке и работает правильно, но когда я пытаюсь войти в систему, у меня всегда появляются сообщения об ошибках, в которых указано неправильное имя пользователя или пароль, даже если это правильно. Я пытался прочитать документацию, но я не нашел решения. И я понятия не имею, что не так.

views.py:

from django.shortcuts import render,redirect
from django.contrib import messages
#from .models import Tutorial
from django.http import HttpResponse
from django.contrib.auth import  logout, authenticate, login, get_user_model # для входа, выхода
from .forms import RegForm , LogForm
from .models import Person, Service, Category
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import AuthenticationForm


@login_required
def homepage(request):
    return render(request = request,
                  template_name='barter/home.html',
                  context = {"category":Category.objects.all})

def register(request):  #вход  аккаунта
    next = request.GET.get('next')
   # if request.method == 'POST':
    form = RegForm(request.POST or None)
    if form.is_valid():
        user = form.save(commit = False)
        Username = form.cleaned_data.get('Username')
        password = form.cleaned_data.get('password')
        user.set_password(password)
        user.save()
        new_user = authenticate(Username=user.Username, password=password)
        login(request, new_user)
        if next:
            return redirect(next)
        return redirect('/')

    context = {
        'form' : form,
    }
    return render(request,"register.html",context)

def login_request(request):  #вход  
    next = request.GET.get('next')
    form = LogForm(request.POST or None)
    if form.is_valid():
        Username = form.cleaned_data.get('Username')
        password = form.cleaned_data.get('password')
        user = authenticate(Username=Username, password=password)
        login(request, user)
        if next:
            return redirect(next)
        return redirect('/')

    context = {
        'form' : form,
    }
    return render(request,"login.html",context)


def logout_request(request): #выход из аккаунта
     logout(request)
     messages.info(request, "Выход из аккаунта совершен!")
     return redirect("/")

models.py:

class Person(AbstractBaseUser):
    p_id = models.AutoField(primary_key = True)
    Username = models.CharField(max_length = 50, unique = True)
    Email = models.CharField(max_length = 50)

    USERNAME_FIELD = 'Username'
    REQUIRED_FIELDS = ['Email'] # то,что требуется при  createsuperuser, must be blank = False

    objects = MyUserManager()   #blank = True = field can be empty

    def __str__(self):
        return self.Username

    def get_Email(self):
        return self.Email

    def has_perm(self, perm, obj=None):   #"Does the user have a specific permission?"

        return True

    def has_module_perms(self, app_label):   #"Does the user have permissions to view the app `app_label`?"
        return True

forms.py:

from django import forms
from barter.models import Person
from django.contrib import messages
from django.contrib.auth import  (logout, authenticate, login, get_user_model)


Person = get_user_model()

class LogForm(forms.Form):
    Username = forms.CharField()
    password = forms.CharField(widget = forms.PasswordInput, label = "Пароль")

    def clean(self,*args, **kwargs):
        Username = self.cleaned_data.get('Username')
        password = self.cleaned_data.get('password')

        if Username and password:
            user = authenticate(Username = Username, password = password)
            if not user:
                raise forms.ValidationError('Username не существует !')
            if user.check_password(password):
                raise forms.ValidationError('Неверный пароль !')
        return super(LogForm, self).clean(*args, **kwargs)


class RegForm(forms.ModelForm):
    password = forms.CharField(widget = forms.PasswordInput, label = "Пароль")
    class Meta:
        model = Person
        fields = [ "Email", "Username","password"]

    def clean(self,*args, **kwargs):
        Username = self.cleaned_data.get('Username')
        password = self.cleaned_data.get('password')
        Email = self.cleaned_data.get('Email')
        Email_p = Person.objects.filter(Email = Email)
        if Email_p.exists():
            raise forms.ValidationError('Аккаунт, привязанный к данному email уже существует !')

manager.py:

from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import PermissionsMixin

class MyUserManager(BaseUserManager):

    def create_user(self, username, email, password=None):

        if not username:
            raise ValueError(_(' Ошибка ! username не установлено !'))
        user = self.model(username=username, email = self.normalize_email(email))
        user.set_password(password)
        user.save(using = self._db)
        return user


    def create_superuser(self, Email, Username, password = None, **extra_fields):
        if not Email:
            raise ValueError("User must have an email")
        if not password :
            raise ValueError("User must have a password")

        user = self.model(Email=self.normalize_email(Email))
        user.Username = Username
        user.set_password(password) 
        user.save(using = self._db)
        return user
...