我试图强制用户在注册时输入他们的电子邮件。我理解如何在ModelForms中使用表单字段。但是,我无法弄清楚如何强制要求现有字段。
我有以下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
答案 0 :(得分:2)
只需覆盖__init__
即可填写电子邮件字段:
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 __init__(self, *args, **kwargs):
super(RegistrationForm, self).__init__(*args, **kwargs)
self.fields['email'].required = True
这样,您不必完全重新定义字段,只需更改属性即可。希望能帮到你。