Как войти в систему пользовательского пользователя в Django

Здравствуйте Это мои модели пользовательского приложения на django,


class Customer(AbstractUser):
    phoneNumber = models.CharField(max_length=30,null=True, blank=True)
    is_active = models.BooleanField(default=True)
    staff = models.BooleanField(default=False,) # a admin user; non super-user
    admin = models.BooleanField(default=False) # a superuser
    groups = None
    user_permissions = None

    def __str__(self):
        return self.username

class Supplier(AbstractUser):
    address = models.TextField(max_length=200)
    phoneNo = models.CharField(max_length=20)
    staff = models.BooleanField(default=False,) # a admin user; non super-user
    admin = models.BooleanField(default=False) # a superuser
    groups = None
    user_permissions = None
    
    def __str__(self):
        return self.username

для чего я хочу реализовать страницу входа, я успешно сделал страницу регистрации с помощью форм

class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm):
        model = Customer
        fields = UserCreationForm.Meta.fields + ('phoneNumber',)
        


class CustomUserChangeForm(UserChangeForm):
    class Meta:
        model = Customer
        fields = UserChangeForm.Meta.fields

class CustomSupplierCreationForm(UserCreationForm):
    class Meta(UserCreationForm):
        model = Supplier
        fields = UserCreationForm.Meta.fields + ('address','phoneNo',)
        


class CustomSupplierChangeForm(UserChangeForm):
    class Meta:
        model = Supplier
        fields = UserChangeForm.Meta.fields

потом используется

class SignUpPage(generic.CreateView):
    form_class = CustomUserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'signup.html'
class SupplierSignUpPage(generic.CreateView):
    form_class = CustomSupplierCreationForm
    success_url = reverse_lazy('login')
    template_name = 'supplier_signup.html'

но я совершенно не понимаю, как реализовать логин, поскольку поиск в doc и google оказался для меня непосильным, пожалуйста, помогите.

  1. Сначала вам нужно добавить метод сохранения в ваш CustomUserCreationForm класс. См. ссылку django-can-i-use-createview-to-create-a-user-object-where-user-is-just-django
  2. .
def save( self, commit = True ) :
  # Save the provided password in hashed format
  user = super( AccountCreationForm, self ).save( commit = False )
  user.set_password( self.cleaned_data[ "password1" ] )
  if commit:
    user.save()
  return user
  1. Вам просто нужно переопределить form_valid() в вашем классе, наследующем CreateView. Вот пример с моим собственным классом. См. django-how-to-login-user-directly-after-registration-using-generic-createview
  2. .
def form_valid(self, form):
  valid = super(CreateArtistView, self).form_valid(form)
  username, password = form.cleaned_data.get('username'), form.cleaned_data.get('password1')
  new_user = authenticate(username=username, password=password)
  login(self.request, new_user)
  return valid
Вернуться на верх