我是 django 的新手,我正在为表单编写基于类的视图。问题是,此表单呈现良好,但发布时我的表单无效。
我不确定我应该怎么做才能让默认验证器验证表单。表单中有两个字段。一个是选择字段,它的选择是根据登录用户动态设置的。另一个是 CharField。不需要验证,因为 CharField 是自由文本,而 ChoiceField 是基于用户的数据。
表格.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)
视图.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)