Уведомления

Группа в Telegram: @pythonsu

#1 Ноя. 9, 2015 12:19:07

Xa_xoo
Зарегистрирован: 2015-08-28
Сообщения: 58
Репутация: +  0  -
Профиль   Отправить e-mail  

django кастомная модель пользователя

Добрый день. Создал свою модель пользователя. Настроил админку. Все работает кроме 1) кнопки “Добавить пользователя” (в веб админке) 2) не отображаются группы и права ( в коде видно, что добавил как filter_horizontal) Подскажите плиз в чем проблема? выдает ошибку при нажатии на кнопку добавить: ‘NoneType’ object is not iterable модель:

class AuthUserManager(BaseUserManager):
def create_user(self, username, email, password=None):
    if not email:
        raise ValueError('User must have email')
    if not username:
        raise ValueError('User must have username')
    user = self.model(username=username, email=self.normalize_email(email))
    user.is_active = True
    user.set_password(password)
    user.save(using=self._db)
    return user
def create_superuser(self, username, email, password):
    user = self.create_user(username=username, email=email, password=password)
    user.is_staff = True
    user.is_superuser = True
    user.save(using=self._db)
    return user
class AuthUser(AbstractBaseUser, PermissionsMixin):
    alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', message='Only alphanumeric characters are allowed.')
    username = models.CharField(unique=True, max_length=30, validators=[alphanumeric])
    email = models.EmailField(verbose_name='email field', unique=True, max_length=255)
    first_name = models.CharField(max_length=50, null=True, blank=True)
    second_name = models.CharField(max_length=50, null=True, blank=True)
    last_name = models.CharField(max_length=50, null=True, blank=True)
    # date_joined = models.DateTimeField(auto_now_add=True)
    date_joined = models.DateTimeField(default=timezone.now())
    is_active = models.BooleanField(default=True, null=False)
    is_staff = models.BooleanField(default=False, null=False)
    # profile_image = models.ImageField(upload_to='uploads', blank=False, default='/static/selfphoto.jpg')
    user_bio = models.TextField()
    perm = models.IntegerField(default=0)
    podr = models.IntegerField(default=0)
    dolznost = models.CharField(max_length=30, null=True, blank=True)
    objects = AuthUserManager()
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']
    def get_full_name(self):
        return '%s %s %s' .format(self.last_name, self.first_name, self.second_name)
    def get_short_name(self):
        return self.username
    def __str__(self):
        return '%s %s %s %s %s' % (self.last_name, self.first_name, self.second_name, self.podr, self.dolznost)
формы:
class AuthUserCreationForm(UserCreationForm):
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password Confirmation', widget=forms.PasswordInput)
class Meta(UserCreationForm.Meta):
    model = AuthUser
    fields = ('email', 'username')
 def clean_username(self):
        username = self.clean_data['username']
        try:
            AuthUser._default_managet.get(username=username)
        except Authuser.DoesNotExist:
            return username
        raise forms.ValidationError(self.error_messages['duplicate_username'])
    def clean_password2(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError('Password do not match.')
        return password2
    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data['password1'])
        if commit:
            user.save()
        return user
class AuthUserChangeForm(UserChangeForm):
    password = ReadOnlyPasswordHashField(label='password', help_text='There is no way too see this password.')
    class Meta(UserChangeForm.Meta):
        model = AuthUser
        fields = ('username', 'email', 'password', 'is_active', 'is_staff', 'is_superuser', 'user_permissions', 'perm')
    def clean_password(self):
        return self.initial['password']
админка:
class AuthUserAdmin(UserAdmin):
form = AuthUserChangeForm
add_form = AuthUserCreationForm
list_display = ('username', 'email', 'is_staff', 'is_superuser',)
list_filter = ('is_superuser',)
fieldsets = (
    (None, {'fields': ('username', 'email', 'password', 'first_name', 'second_name', 'last_name', 'date_joined', 'user_bio', 'podr', 'dolznost')}),
    ('Permissions', {'fields': ('is_active', 'is_superuser', 'is_staff', 'perm')}),
)
add_fieldsets = (
    (None, {
        'classes': ('wide',),
        'fields': ('username', 'email', 'password1', 'password2', 'is_stuff', 'is_superuser', 'perm')
    })
)
search_fields = ('username', 'email')
ordering = ('username',)
filter_horizontal = ('groups', 'user_permissions')

Офлайн

Board footer

Модераторировать

Powered by DjangoBB

Lo-Fi Version