I m new to django, I m writing a class-based view for a form.
The problem is, this form renders well, but when posting I get form invalid.
I am not sure what should I do to get default validators validate the form. There are two fields in the form. One is choice field, whose choices are set dynamically based on logged-in user. Another is CharField. There is no need of validation as CharField is free text and ChoiceField is based on user’s data.
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)
I guess the problem is when you create the form instance, you forget to pass the request.POST data to your form class, the get_form method should be:
Or, I think the better way for get_form is:
Check the the source code of get_form_kwargs method in django.views.generic.edit.FormMixin, it automatically handle the request’s PUT/POST data and files for you.