@robocop45
Only python

Убрав пароль в AbstractBaseUser, не могу зайти в админку, как исправить?

Задача: регистрация/вход без пароля. Использовать только username и photo

models
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)
# Create your models here.
#user's part
class UserManager(BaseUserManager):
    def create_user(self, username):
        normalized_username = username.lower()
        """
        Creates and saves a User with the given email and password.
        """
        if not username:
            raise ValueError('Users must have an username ')

        user = self.model()


        user.save(using=self._db)
        return user

    def create_staffuser(self, username):
        """
        Creates and saves a staff user with the given email and password.
        """
        user = self.create_user(
            username,

        )
        user.staff = True
        user.save(using=self._db)
        return user

    def create_superuser(self, username):
        """
        Creates and saves a superuser with the given email and password.
        """
        user = self.create_user(
            username,

        )
        user.staff = True
        user.admin = True
        user.save(using=self._db)
        return user

class User(AbstractBaseUser):
    username = models.CharField(
        verbose_name='username',
        max_length=255,
        unique=True
    )
    main_img = models.ImageField(upload_to='main_imgs/%Y/%m', verbose_name='Главное фото')
    checking_photo = models.ImageField(upload_to='checking_photo/%Y/%m', verbose_name='Временное фото для проверки ')

    is_active = models.BooleanField(default=True)
    staff = models.BooleanField(default=False) # a admin user; non super-user
    admin = models.BooleanField(default=False) # a superuser
    password = None
    # notice the absence of a "Password field", that is built in.
    objects = UserManager()
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = [] # Email & Password are required by default.

    def get_full_name(self):
        # The user is identified by their email address
        return self.username

    def get_short_name(self):
        # The user is identified by their email address
        return self.username

    def __str__(self):
        return self.username

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

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

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        return self.staff

    @property
    def is_admin(self):
        "Is the user a admin member?"
        return self.admin


forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm,AuthenticationForm

from account.models import User
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import ReadOnlyPasswordHashField

User = get_user_model()

class RegisterForm(forms.ModelForm):
    """
    The default

    """
    class Meta:
        model = User
        fields = ['username']

    def clean_email(self):
        '''
        Verify email is available.
        '''
        email = self.cleaned_data.get('username')
        qs = User.objects.filter(email=email)
        if qs.exists():
            raise forms.ValidationError("username is taken")
        return email

    # def clean(self):
    #     '''
    #     Verify both passwords match.
    #     '''
    #     cleaned_data = super().clean()
    #     password = cleaned_data.get("password")
    #     password_2 = cleaned_data.get("password_2")
    #     if password is not None and password != password_2:
    #         self.add_error("password_2", "Your passwords must match")
    #     return cleaned_data


class UserAdminCreationForm(forms.ModelForm):
    """
    A form for creating new users. Includes all the required
    fields, plus a repeated password.
    """
    # password = forms.CharField(widget=forms.PasswordInput)
    # password_2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ['username']

    # def clean(self):
    #     '''
    #     Verify both passwords match.
    #     '''


    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super().save(commit=False)
        # user.set_password(self.cleaned_data["password"])
        if commit:
            user.save()
        return user


class UserAdminChangeForm(forms.ModelForm):
    """A form for updating users. Includes all the fields on
    the user, but replaces the password field with admin's
    password hash display field.
    """
    # password = ReadOnlyPasswordHashField()

    class Meta:
        model = User
        fields = ['username',  'is_active', 'admin']


миграции прошли успешно, создал супер пользователя и во время этого программа потребовала только username

Но я не могу войти в админку, требует пароль. пробовал убрать поле пароля в файле
django/contrib/admin/templates/admin/login.html но это не помогло

649c5df09f4b2557854945.png
  • Вопрос задан
  • 125 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы