Reputation: 7302
I'm creating a form without model. Here is my form class:
class LinkAssetsForm(forms.Form):
preview = forms.ChoiceField()
thumbnail = forms.ChoiceField()
banner = forms.ChoiceField()
def __init__(self, *args, **kwargs):
super(LinkAssetsForm, self).__init__()
filepod = kwargs.get('filepod',None)
if filepod is not None:
fp_util = FilePodUtil()
preview_files = fp_util.get_files_from_filepod(filepod, ['mov'])
thumbnail_files = fp_util.get_files_from_filepod(filepod, ['jpg'])
banner_files = fp_util.get_files_from_filepod(filepod, ['jpg'])
self.fields['preview'].choices = [(x.fullpath, x.name) for x in preview_files]
self.fields['thumbnail'].choices = [(x.fullpath, x.name) for x in thumbnail_files]
self.fields['banner'].choices = [(x.fullpath, x.name) for x in banner_files]
My template:
<form role="form" id="form-content" class="form-horizontal" method="post">
{% csrf_token %}
{% bootstrap_form form layout="horizontal" %}
{% url 'delivery:delivery-detail' delivery.id as cancel_url %}
<div class="form-group formAction">
<div class="col-sm-offset-3 col-sm-9">
<div class="rc-faGroupPrimary">
{% bootstrap_button "Save" button_type="submit" button_class="btn-primary" size="lg" %}
</div>
{% bootstrap_button "Cancel" button_type="link" button_class="btn-default" href=cancel_url %}
</div>
</div>
</form>
In my view:
def post(self, request, *args, **kwargs):
form = LinkAssetsForm(request.POST)
if form.is_valid():
print 'VALID=====>>>>>>>>>>'
data = form.cleand_data
#TODO: save the data
messages.add_message(self.request, messages.SUCCESS, "Assets linked successfully.")
return redirect(reverse('delivery:delivery-content-link-assets', args=[self.kwargs['delivery_id'],self.kwargs['content_id']]))
else:
print 'INVALID=====>>>>>>>>>>'
messages.add_message(self.request, messages.ERROR, "Select all the required fields.")
My problem is that the form never passes the if form.is_valid()
condition. The form renders properly, I choose the value in the combo boxes, submit to the right address, etc.. and it always fails the validation.
Can you see what I am missing?
Thanks for any help.
Upvotes: 0
Views: 891
Reputation: 308849
You have forgotten to pass args and kwargs when you call super()
. It should be:
def __init__(self, *args, **kwargs):
super(LinkAssetsForm, self).__init__(*args, **kwargs)
Upvotes: 2
Reputation: 2146
I've found in cases where the form is never being validated, it is because it's requiring all fields in cases where they are not always necessary. Setting required=False inside your form fields i.e.:
banner = forms.ChoiceField(required=False)
may help if you won't always be passing in values to the fields.
Upvotes: 0
Reputation: 442
You could try to add
{{ form.errors }}
{{ form.non_field_errors }}
to template display the errors - this could give you a hint.
P.S. "cleand_data" - is it a typo?
Upvotes: 1