我新來django,我寫一個基於類的視圖的表單。 問題是,這個表格呈現得很好,但是當我發佈表單無效時。Django綁定窗體無效 - 如何獲取默認驗證工作?
我不知道該怎麼做才能讓默認驗證器驗證表單。表單中有兩個字段。一個是選擇字段,其選擇根據登錄用戶動態設置。另一個是CharField。由於CharField是自由文本,ChoiceField基於用戶數據,因此不需要驗證。
forms.py
class HomeForm(forms.Form):
phones= forms.ChoiceField(label='Select phone', choices =(), required=True)
message = forms.CharField(max_length=10, required=True)
def __init__(self, user, *args, **kwargs):
super(HomeForm, self).__init__(*args, **kwargs)
print >> sys.stderr, 'form init'
self.fields['phones'].choices = [(ids.id, ids.phone_model.short_name) for ids in GCM_RegId.objects.filter(user=user)]
def process(self, user):
cd = self.cleaned_data
regid_id = cd['phones'].value
gcm_regid = GCM_RegId.objects.filter(id=regid_id)
views.py
class HomeView(FormView):
template_name = "home.html"
form_class = HomeForm
success_url = 'home'
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
if(form.is_bound):
print >> sys.stderr, "Form is Bound"
else:
print >> sys.stderr, "Form is NOT Bound"
if form.is_valid():
print >> sys.stderr, "Form Valid"
return self.form_valid(form)
else:
print >> sys.stderr, "Form NOT Valid"
return self.form_invalid(form, **kwargs)
def get_form(self, form_class):
form = HomeForm(self.request.user, {})
return form
def form_valid(self, form):
form.process(self.request.user)
print >> sys.stderr, "RegIdSubmitView form_valid"
return super(HomeView, self).form_valid(form)
你在推翻事物。具體來說,你誤解了Django的視圖設計,並破壞了FormMixin的幾個特性。我建議你看看[通用編輯視圖]的源代碼(https://github.com/django/django/blob/master/django/views/generic/edit.py)。沒有必要重寫HTTP方法處理程序('ProcessFormView'),除非您對錶單處理的解釋需要別的東西 - 重點在於重寫FormMixin的方法來添加自定義功能,但要確保不要忽略任何基本功能。 – 2012-08-02 07:15:51