Django:为django-registration添加另一个字段
我刚接触Django,对django-registration有点迷茫。目前我已经把django-registration设置好了,但我想在注册时添加一个手机号的字段。我需要在注册表单里加上手机号,这样我就可以用Twilio的API通过短信发送验证链接,而不是通过邮件。请问我该怎么在django-registration里添加这个字段呢?
2 个回答
1
我之前没有用django-registration,而是自己改过django-userena,给注册表单加了一个自定义字段。
你可以在这里查看代码:这里。
我相信在django-registration中,过程大致也是一样的:重写注册表单并添加自定义字段。
不过,我觉得django-registration现在已经不再维护了。它是个经典的工具,运行得很好,但还有其他选择。
1
我在工作中使用django,遇到这种问题时,我们通常会给用户添加一个模型,举个例子:
- 你可以创建一个新的模型,比如叫做profile(个人资料),并且用一个OneToOneField(单一关系字段)把它和用户关联起来。
- 在这个profile模型中添加你想要的字段,比如电话、国家、语言、日志等等。
- 创建一个admin.py文件来管理这个模型(profile),这样你就可以在django的管理后台同时管理用户和这个模型了。
个人资料模型示例
class Profile(models.Model):
user = models.OneToOneField(User)
phone = models.CharField(max_length=255, blank=True, null=True, verbose_name='phone')
description = models.TextField(blank=True, verbose_name='descripction')
...
...
class Meta:
ordering = ['user']
verbose_name = 'user'
verbose_name_plural = 'users'
admin.py示例
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
class ProfileInline(admin.StackedInline):
model = Profile
can_delete = False
filter_horizontal = ['filter fields'] # example: ['tlf', 'country',...]
verbose_name_plural = 'profiles'
fk_name = 'user'
class UserAdmin(UserAdmin):
inlines = (ProfileInline, )
list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
list_filter = ('is_staff', 'is_superuser', 'is_active')
admin.site.unregister(User) # Unregister user to add new inline ProfileInline
admin.site.register(User, UserAdmin) # Register User with this inline profile
创建一个用户并给他添加个人资料
# Create user
username = 'TestUser'
email = 'test@example.com'
passw = '1234'
new_user = User.objects.create_user(username, email, passw)
# Create profile
phone = '654654654'
desc = 'Test user profile'
new_profile = Profile(user=new_user, phone = phone, description=desc)
new_profile.profile_role = new_u_prole
new_profile.user = new_user
# Save profile and user
new_profile.save()
new_user.save()
现在你就会发现这个Profile模型和每个用户都关联在一起了,你可以在Profile模型中添加你想要的字段。比如,如果你执行:
user = User.objects.get(id=1)
你可以通过以下方式访问他的个人资料:
user.profile
如果想访问电话,可以这样做:
user.profile.phone