0
我试图强制用户在注册时输入他们的电子邮件。我了解如何通过ModelForms使用表单字段。但是,我无法弄清楚如何强制要求现有的字段。如何获得基本Django用户模型中的电子邮件字段?
我有以下的ModelForm:
class RegistrationForm(UserCreationForm):
"""Provide a view for creating users with only the requisite fields."""
class Meta:
model = User
# Note that password is taken care of for us by auth's UserCreationForm.
fields = ('username', 'email')
我使用下面的视图来处理我的数据。我不确定它有多相关,但值得一提的是其他字段(用户名,密码)正确加载错误。但是,用户模型已经根据需要设置了这些字段。
def register(request):
"""Use a RegistrationForm to render a form that can be used to register a
new user. If there is POST data, the user has tried to submit data.
Therefore, validate and either redirect (success) or reload with errors
(failure). Otherwise, load a blank creation form.
"""
if request.method == "POST":
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
# @NOTE This can go in once I'm using the messages framework.
# messages.info(request, "Thank you for registering! You are now logged in.")
new_user = authenticate(username=request.POST['username'],
password=request.POST['password1'])
login(request, new_user)
return HttpResponseRedirect(reverse('home'))
else:
form = RegistrationForm()
# By now, the form is either invalid, or a blank for is rendered. If
# invalid, the form will sent errors to render and the old POST data.
return render_to_response('registration/join.html', { 'form':form },
context_instance=RequestContext(request))
我已经尝试在RegistrationForm中创建一个电子邮件字段,但这似乎没有效果。我是否需要扩展用户模型并覆盖电子邮件字段?还有其他选择吗?
感谢,
ParagonRG
太棒了!这似乎工作。我没有意识到有一个'必需'属性。在这个例子中,你正在重写哪个__init__? UserCreationForm的init函数,最终继承(通过一些父母)ModelForm类? – Paragon 2012-04-22 04:45:35
我也发现了这个StackOverflow问题,它提供了一个非常类似的问题的答案:http://stackoverflow.com/questions/1134667/django-required-field-in-model-form。 – Paragon 2012-04-22 04:47:32
我并不是解释超级调用的最佳人选,但简而言之,''__init__''方法执行'UserCreationForm'中定义的所有内容,然后执行'RegistrationForm .__ init__中定义的内容'' – Brandon 2012-04-22 04:55:36