[英]How can I get the email field in the basic Django User model to be required?
我試圖強迫用戶在注冊時輸入他們的電子郵件。 我了解如何在 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
這樣,您不必完全重新定義字段,而只需更改屬性。 希望能幫到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.