django之扩展默认用户表使用邮箱账户登录
auth.py代码
from django.contrib.auth.models import BaseUserManager,AbstractBaseUser,Group,PermissionsMixin
class UserManager(BaseUserManager):
def create_user(self,email,name,password=None):
if not email:
raise ValueError("用户名必须是邮箱地址")
user = self.model(
email=self.normalize_email(email),
name=name,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self,email,name,password):
user = self.create_user(email,
password=password,
name=name,
)
user.is_superuser = True
user.save(using=self._db)
return user
model.py代码
from django.db import models
import django
from asset.models import HostGroup,Assets
from index import auth
# Create your models here.
class UserProfile(auth.AbstractBaseUser,auth.PermissionsMixin):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
is_active = models.BooleanField(default=True)
objects = auth.UserManager()
name = models.CharField(max_length=32)
memo = models.TextField('备注', blank=True, null=True, default=None)
date_joined = models.DateTimeField(blank=True, null=True, auto_now_add=True)
valid_begin_time = models.DateTimeField(default=django.utils.timezone.now, help_text="yyyy-mm-dd HH:MM:SS")
valid_end_time = models.DateTimeField(blank=True, null=True, help_text="yyyy-mm-dd HH:MM:SS")
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name']
def get_full_name(self):
# The user is identified by their email address
return self.email
def get_short_name(self):
# The user is identified by their email address
return self.email
@property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_active
def __str__(self):
return self.email
class Meta:
db_table = 'userprofile'
verbose_name = '用户信息'
verbose_name_plural = u"用户信息"
admin.py代码
from django.contrib import admin
from django import forms
from index import models
from django.contrib.auth import password\_validation
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
class UserCreationForm(forms.ModelForm):
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = models.UserProfile
fields = ('email','name')
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
#self.instance.username = self.cleaned_data.get('email')
#password_validation.validate_password(self.cleaned_data.get['password2'],self.instance)
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
password = ReadOnlyPasswordHashField()
class Meta:
model = models.UserProfile
fields = ('email', 'password', 'name','is_active', 'is_superuser')
def clean_password(self):
return self.initial["password"]
class UserProfileAdmin(BaseUserAdmin):
# The forms to add and change user instances
form = UserChangeForm
add_form = UserCreationForm
list_display = ('id', 'email', 'name','is_superuser', 'is_active')
list_filter = ('is_superuser',)
fieldsets = (
(None, {'fields': ('email', 'name', 'password')}),
('Personal info', {'fields': ('name')}),
('Permissions', {'fields': ('is_active','is_superuser', )}),
('用户其它权限', {'fields': ('user_permissions',)}),
('账户有效期', {'fields': ('valid_begin_time', 'valid_end_time')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2','name')}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ('bind_hosts', 'user_permissions', 'groups')
admin.site.register(models.UserProfile)
setting.py代码 …
AUTH_USER_MODEL = 'index.UserProfile' #index是你的app名称。Userprofile是你的model表
…
django之扩展默认用户表使用邮箱账户登录
http://www.jcwit.com/article/153/