我已经阅读了很多关于如何在使用 Django 注册时添加额外字段的内容,例如这里、这里和这里。代码片段是:forms.py(来自注册应用程序)
class RegistrationForm(forms.Form):
username = forms.RegexField(regex=r'^\w+$', max_length=30, widget=forms.TextInput(attrs=attrs_dict), label=_("Username"), error_messages={ 'invalid': _("This value must contain only letters, numbers and underscores.") })
email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=75)), label=_("Email"))
password1=forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_("Password"))
institute=forms.CharField(max_length=50) #This is the new!
password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_("Password (again)"))
captcha = CaptchaField()
我使用 django 的注册保存方法,在默认后端:
def register(self, request, **kwargs):
username, email, password = kwargs['username'], kwargs['email'], kwargs['password1']
if Site._meta.installed:
site = Site.objects.get_current()
else:
site = RequestSite(request)
new_user = RegistrationProfile.objects.create_inactive_user(username, email,
password, site)
signals.user_registered.send(sender=self.__class__,
user=new_user,
request=request)
return new_user
在 models.py 我创建了一个新类:
class UserProfile(models.Model):
user = models.OneToOneField(User)
institute=models.CharField(max_length=50)
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile, created = UserProfile.objects.get_or_create(user=instance)
post_save.connect(create_user_profile, sender=User)
在 admin.py 中:
admin.site.unregister(User)
class UserProfileInline(admin.StackedInline):
model = UserProfile
class UserProfileAdmin(UserAdmin):
inlines = [ UserProfileInline, ]
admin.site.register(User, UserProfileAdmin)
我也没有改变任何东西。当我渲染表单时,我可以看到我添加的 Institute Field。当我在管理站点中时,我可以看到每个用户的用户配置文件。但是,当我创建新用户时,没有保存任何内容,而用户的其他详细信息通常会被保存。我认为我需要某种配置,但在哪里?也许在 Django-registration 应用程序的文件中?