我正在尝试强迫用户在注册时输入电子邮件。我了解一般如何在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
只需覆盖__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
这样,您不必完全重新定义字段,而只需更改属性。希望对您有帮助。
使用init进行正确的更改仅对呈现的表单进行更改,并且可以使用Burp Suite等拦截工具来绕过这些表单?还是也将阻止在POST请求后在后端(服务器端)添加没有此字段的用户?