admin add user fixed. !!!Please recreate database!!!

remotes/origin/yandex
Bachurin Sergey 12 years ago
parent 447eac32e1
commit fee98da4e5
  1. 33
      project/myauth/admin.py
  2. 28
      project/myauth/forms.py
  3. 30
      project/myauth/managers.py
  4. 61
      project/myauth/models.py

@ -1,12 +1,35 @@
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import ugettext_lazy as _
from models import DokUser
from forms import CustomUserChangeForm, CustomUserCreationForm
import models
class CustomUserAdmin(UserAdmin):
# as an example, this custom user admin orders users by email address
ordering = ('email',)
# The forms to add and change user instances
admin.site.register(models.DokUser, CustomUserAdmin)
# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference the removed 'username' field
fieldsets = (
(None, {'fields': ('username', 'email', 'password')}),
(_('Personal info'), {'fields': ('first_name', 'last_name')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions')}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'email', 'password1', 'password2')}
),
)
form = CustomUserChangeForm
add_form = CustomUserCreationForm
list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
search_fields = ('username', 'email', 'first_name', 'last_name')
ordering = ('email',)
#admin.site.register(models.DokUser)
admin.site.register(DokUser, CustomUserAdmin)

@ -5,9 +5,11 @@ from django.contrib.auth import authenticate
from project.commons.forms import set_field_error
from project.customer import consts as customer_consts
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from models import DokUser
PASSWORD_MIN_LEN = getattr(settings, 'PASSWORD_MIN_LEN ', 7)
PROFILE_CHOICES = (
@ -178,3 +180,29 @@ class LoginForm(forms.Form):
def get_user(self):
return self.user_cache
class CustomUserCreationForm(UserCreationForm):
"""
A form that creates a user, with no privileges, from the given email and
password.
"""
def clean_username(self):
# Since User.username is unique, this check is redundant,
# but it sets a nicer error message than the ORM. See #13147.
username = self.cleaned_data["username"]
try:
DokUser._default_manager.get(username=username)
except DokUser.DoesNotExist:
return username
raise forms.ValidationError(self.error_messages['duplicate_username'])
class Meta:
model = DokUser
fields = ("username", "email",)
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = DokUser

@ -2,7 +2,9 @@
import hashlib
from random import random
from django.utils import timezone
from django.db import models
from django.contrib.auth.models import BaseUserManager
class ConfirmEmailManager(models.Manager):
@ -26,3 +28,31 @@ class ResetKeyManager(models.Manager):
reset_key.key = key # обновить ключ
reset_key.save()
return reset_key
class CustomUserManager(BaseUserManager):
def _create_user(self, username, email, password,
is_staff, is_superuser, **extra_fields):
"""
Creates and saves a User with the given email and password.
"""
now = timezone.now()
if not email :
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email,
username=username,
is_staff=is_staff, is_active=True,
is_superuser=is_superuser, last_login=now,
date_joined=now, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, username, email, password=None, **extra_fields):
return self._create_user(username, email, password, False, False,
**extra_fields )
def create_superuser(self, username, email, password, **extra_fields):
return self._create_user(username, email, password, True, True,
**extra_fields)

@ -2,20 +2,67 @@
from django.db import models
from django.conf import settings
from django.core.validators import RegexValidator, MinLengthValidator
from django.contrib.auth.models import AbstractUser
#from django.contrib.auth.models import AbstractUser
from django.utils import timezone
from django.utils.http import urlquote
from django.utils.translation import ugettext_lazy as _
from django.core.mail import send_mail
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
import managers
class DokUser(AbstractUser):
"""Самопальная модель пользователя"""
class DokUser(AbstractBaseUser, PermissionsMixin):
"""(не)Самопальная модель пользователя - содрано у caktusgroup.com,
также проблемы с добавлением юзера в админке решены при помощи
stackoverflow, да хранит гугл имя его.
"""
username = models.CharField(_('first name'), max_length=30, blank=True, unique=True)
email = models.EmailField(_('email address'), max_length=254, unique=True)
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
is_staff = models.BooleanField(_('staff status'), default=False,
help_text=_('Designates whether the user can log into this admin '
'site.'))
is_active = models.BooleanField(_('active'), default=True,
help_text=_('Designates whether this user should be treated as '
'active. Unselect this instead of deleting accounts.'))
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
profile = models.ForeignKey('customer.UserProfile', null=True, related_name='users')
def has_perm(perm, obj=None):
return True
objects = managers.CustomUserManager()
def has_module_perms(self, app_label):
return True
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def get_absolute_url(self):
return "/users/%s/" % urlquote(self.email)
def get_full_name(self):
"""
Returns the first_name plus the last_name, with a space in between.
"""
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
"Returns the short name for the user."
return self.first_name
def email_user(self, subject, message, from_email=None):
"""
Sends an email to this User.
"""
send_mail(subject, message, from_email, [self.email])
# def has_perm(perm, obj=None):
# return True
#
# def has_module_perms(self, app_label):
# return True
class ConfirmEmail(models.Model):

Loading…
Cancel
Save