我使用内置的注册和激活功能发送令牌激活电子邮件来注册用户。register表单子类化UserCreationForm,为电子邮件和出生日期验证添加额外字段。我的代码如下:
在表单.py公司名称:
class UserRegisterForm(UserCreationForm):
date_of_birth = forms.DateField(widget=forms.SelectDateWidget(years=range(2017, 1900, -1)))
email = forms.EmailField(required=True)
def clean_username(self):
username = self.cleaned_data.get('username')
if User.objects.filter(username__iexact=username).exists():
raise forms.ValidationError('Username already exists')
return username
def clean_date_of_birth(self):
'''
Only accept users aged 13 and above
'''
userAge = 13
dob = self.cleaned_data.get('date_of_birth')
today = date.today()
if (dob.year + userAge, dob.month, dob.day) > (today.year, today.month, today.day):
raise forms.ValidationError('Users must be aged {} years old or above.'.format(userAge))
return dob
def clean_email(self):
email = self.cleaned_data.get('email')
if User.objects.filter(email__iexact=email).exists():
raise forms.ValidationError('A user has already registered using this email')
return email
def clean_password2(self):
'''
we must ensure that both passwords are identical
'''
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
raise forms.ValidationError('Passwords must match')
return password2
class Meta:
model = User
fields = ['username', 'email', 'date_of_birth', 'password1', 'password2']
在视图.py公司名称:
^{pr2}$在模型.py公司名称:
class UserProfile(models.Model):
'''
Extends the Django User model
'''
user = models.OneToOneField(settings.AUTH_USER_MODEL,
related_name='profile')
email = models.EmailField(blank=True)
date_of_birth = models.DateField(blank=True, null=True)
profile_photo = models.ImageField(blank=True)
following = models.ManyToManyField(settings.AUTH_USER_MODEL,
blank=True,
related_name='followed_by')
def __str__(self):
return 'Followers({});Following({})'.format(self.user.followed_by.all().count(),self.get_following().count())
def post_save_user_receiver(sender, instance, created, *args, **kwargs):
'''
Django signals to automatically create
a user profile when a user object is created
'''
if created:
new_profile, is_created = UserProfile.objects.get_or_create(user=instance)
post_save.connect(post_save_user_receiver, sender=settings.AUTH_USER_MODEL)
在管理员py公司名称:
from django.contrib import admin
from .models import UserProfile
class ProfileAdmin(admin.ModelAdmin):
list_display = ['user', 'id', 'date_of_birth', 'profile_photo', '__str__']
admin.site.register(UserProfile, ProfileAdmin)
新用户已正确注册。但是,只有用户名和电子邮件字段出现在Django管理站点的Users部分。我不明白为什么新注册用户的出生日期字段没有显示。在
您没有扩展用户模型,而是添加了相关的用户配置文件。实际上,您不需要在任何地方创建此用户配置文件的实例或使用表单中的数据填充它们;您可以在视图中获得DOB和email值,但随后忽略它们。在
您需要使用以下值创建配置文件:
date_of_birth
字段属于UserProfile
模型,因此不应将其包含在用户表单的fields
中。在在您的视图中,您可以获得由您的信号创建的配置文件,并设置出生日期,您可以从已清理的数据中获取。在
^{pr2}$相关问题 更多 >
编程相关推荐