Форум сайта python.su
Добрый день.
Возникла не понятная ошибка… создал свою модель пользователя
модель:
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.creat_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) 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/defaultprofileimage.png') user_bio = models.TextField() 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 self.email
AUTH_USER_MODEL = 'app.models.AuthUser'
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') 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', 'firs_name', 'second_name', 'last_name', 'user_bio')}), ('Permissions', {'fields': ('is_active', 'is_superuser', 'is_staff')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('username', 'email', 'password1', 'password2', 'is_stuff', 'is_superuser') }) ) search_fields = ('username', 'email') ordering = ('email',) filter_horizontal = ('groups', 'user_permissions') admin.site.register(AuthUser, AuthUserAdmin)
Отредактировано Xa_xoo (Окт. 21, 2015 11:49:10)
Прикреплённый файлы: 1.png (45,7 KБ)
Офлайн
AUTH_USER_MODEL = ‘app.models.AuthUser’
Офлайн
DOOMerочередной раз благодарю, ошибка не появляется
Офлайн
почти добил.. осталась последняя проблема. В web администраторе не могу добавить нового пользователя.. при нажатии Добавить выдает ошибку:
TyprError: ‘NoneType’ object is not iterable
не пойму вроде в class AuthUserCreationForm(UserCreationForm) описано все верно… изменять дает, а добавлять нет..
в shell`e пользователей добавляет и отображает в веб админке
Офлайн
Xa_xoo, полный трейсбк можно увидеть?
Офлайн
Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/app/authuser/add/ Django Version: 1.8.3 Python Version: 3.4.3 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mainnews', 'app') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "C:\Python34\lib\site-packages\django-1.8.3-py3.4.egg\django\core\handlers\base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python34\lib\site-packages\django-1.8.3-py3.4.egg\django\contrib\admin\options.py" in wrapper 616. return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Python34\lib\site-packages\django-1.8.3-py3.4.egg\django\utils\decorators.py" in _wrapped_view 110. response = view_func(request, *args, **kwargs) File "C:\Python34\lib\site-packages\django-1.8.3-py3.4.egg\django\views\decorators\cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "C:\Python34\lib\site-packages\django-1.8.3-py3.4.egg\django\contrib\admin\sites.py" in inner 233. return view(request, *args, **kwargs) File "C:\Python34\lib\site-packages\django-1.8.3-py3.4.egg\django\utils\decorators.py" in _wrapper 34. return bound_func(*args, **kwargs) File "C:\Python34\lib\site-packages\django-1.8.3-py3.4.egg\django\views\decorators\debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "C:\Python34\lib\site-packages\django-1.8.3-py3.4.egg\django\utils\decorators.py" in bound_func 30. return func.__get__(self, type(self))(*args2, **kwargs2) File "C:\Python34\lib\site-packages\django-1.8.3-py3.4.egg\django\utils\decorators.py" in _wrapper 34. return bound_func(*args, **kwargs) File "C:\Python34\lib\site-packages\django-1.8.3-py3.4.egg\django\utils\decorators.py" in _wrapped_view 110. response = view_func(request, *args, **kwargs) File "C:\Python34\lib\site-packages\django-1.8.3-py3.4.egg\django\utils\decorators.py" in bound_func 30. return func.__get__(self, type(self))(*args2, **kwargs2) File "C:\Python34\lib\contextlib.py" in inner 30. [b] return func(*args, **kwds)[/b] File "C:\Python34\lib\site-packages\django-1.8.3-py3.4.egg\django\contrib\auth\admin.py" in add_view 121. extra_context) File "C:\Python34\lib\site-packages\django-1.8.3-py3.4.egg\django\contrib\admin\options.py" in add_view 1516. return self.changeform_view(request, None, form_url, extra_context) File "C:\Python34\lib\site-packages\django-1.8.3-py3.4.egg\django\utils\decorators.py" in _wrapper 34. return bound_func(*args, **kwargs) File "C:\Python34\lib\site-packages\django-1.8.3-py3.4.egg\django\utils\decorators.py" in _wrapped_view 110. response = view_func(request, *args, **kwargs) File "C:\Python34\lib\site-packages\django-1.8.3-py3.4.egg\django\utils\decorators.py" in bound_func 30. return func.__get__(self, type(self))(*args2, **kwargs2) File "C:\Python34\lib\contextlib.py" in inner 30. [b]return func(*args, **kwds)[/b] File "C:\Python34\lib\site-packages\django-1.8.3-py3.4.egg\django\contrib\admin\options.py" in changeform_view 1456. ModelForm = self.get_form(request, obj) File "C:\Python34\lib\site-packages\django-1.8.3-py3.4.egg\django\contrib\auth\admin.py" in get_form 79. return super(UserAdmin, self).get_form(request, obj, **defaults) File "C:\Python34\lib\site-packages\django-1.8.3-py3.4.egg\django\contrib\admin\options.py" in get_form 675. fields = flatten_fieldsets(self.get_fieldsets(request, obj)) File "C:\Python34\lib\site-packages\django-1.8.3-py3.4.egg\django\contrib\admin\utils.py" in flatten_fieldsets 101. for name, opts in fieldsets: Exception Type: TypeError at /admin/app/authuser/add/ Exception Value: 'NoneType' object is not iterable
Отредактировано Xa_xoo (Окт. 21, 2015 15:34:25)
Офлайн
я думаю по той же причине не отображается в интерфейсе редактирования поьзователя возможность добавить пользоваетля в группу .. (группу создал, а связать нельзя)
Офлайн
Xa_xoo, проблема где-то в коде формы. добавления, онанепередается в административную вьюху создания пользователя.
Офлайн