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