Django formset doesn't validate - django

I am trying to save a formset but it seems to be bypassing is_valid() even though there are required fields.
To test this I have a simple form:
class AlbumForm(forms.Form):
name = forms.CharField(required=True)
The view:
#login_required
def add_album(request, artist):
artist = Artist.objects.get(slug__iexact=artist)
AlbumFormSet = formset_factory(AlbumForm)
if request.method == 'POST':
formset = AlbumFormSet(request.POST, request.FILES)
if formset.is_valid():
return HttpResponse('worked')
else:
formset = AlbumFormSet()
return render_to_response('submissions/addalbum.html', {
'artist': artist,
'formset': formset,
}, context_instance=RequestContext(request))
And the template:
<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
{{ formset.management_form }}
{% for form in formset.forms %}
<ul class="addalbumlist">
{% for field in form %}
<li>
{{ field.label_tag }}
{{ field }}
{{ field.errors }}
</li>
{% endfor %}
</ul>
{% endfor %}
<div class="inpwrap">
<input type="button" value="add another">
<input type="submit" value="add">
</div>
</form>
What ends up happening is I hit "add" without entering a name then HttpResponse('worked') get's called seemingly assuming it's a valid form.
I might be missing something here, but I can't see what's wrong. What I want to happen is, just like any other form if the field is required to spit out an error if its not filled in. Any ideas?

Heh, I was having this exact same problem. The problem is that you're using a formset!! Formsets allow all fields in a form to be blank. If, however, you have 2 fields, and fill out only one, then it will recognize your required stuffs. It does this because formsets are made for "bulk adding" and sometimes you don't want to fill out all the extra forms on a page. Really annoying; you can see my solution here.

For each of the fields that are required, add an extra entry in the attrs parameter
resident_status = forms.ChoiceField(widget=forms.Select(
attrs={'class': 'form-control', 'required': 'required'}), choices=President.RESIDENT_STATUS,
required=True)
As you can see, I maintain the required=True for django's form validation but specify 'required':'required' for the template to insist for the field be required.
Hope that helps.

Add 2 lines.
if request.method == 'POST':
def initial_form_count(self): return 10 # the number of forms
AlbumFormSet.initial_form_count = initial_form_count
formset = AlbumFormSet(request.POST, request.FILES)
Good luck!

use:
if not any(formset.errors): ...
instead of:
if formset.is_valid(): ...

Related

Generating forms based on user choices in Django

I am working on a Django project whose purpose is to allow the user to fill in some forms. In some of these forms, the user must make a choice between several options and, based on the choice made, a particular form must be generated. At the end of all these forms, the data entered must be used to write a pdf file.
As for the functionality related to generating the pdf, what I'm interested in for the purposes of the question is the use of data entered in one view in another view using them as context.
Here's what I tried to do.
First of all I created some forms in forms.py:
class ChoiceForm(forms.Form):
CHOICES = [
('1', 'Choice-One'),
('2', 'Choice Two'),
]
choice = forms.ChoiceField(choices=CHOICES)
class ChoiceOneForm(forms.Form):
name_one = forms.CharField(max_length=200)
class ChoiceTwoForm(forms.Form):
name_two = forms.CharField(max_length=200)
Then I created this view in views.py:
def contact(request):
if request.method == 'POST':
num_people = int(request.POST.get('num_people'))
people_formset = [forms.ChoiceForm() for i in range(num_people)]
return render(request, 'home.html', {'people_formset': people_formset})
else:
return render(request, 'home.html')
def generate_pdf(request):
context = {}
return render(request, 'pdf.html', context)
And finally I have this HTML file called 'home.html':
<h1>Contact</h1>
<form method="post">
{% csrf_token %}
People number: <input type="number" name="num_people" required>
<input type="submit" value="Submit">
</form>
{% if people_formset %}
{% for form in people_formset %}
<form>
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
{% endfor %}
{% endif %}
what I've been able to achieve so far is to generate as many 'choice' fields as the value of the number entered in the 'num_people' field.
What I'm missing is:
1. Being able to create, for each 'choiche' field in the formset, a ChoiceOneForm or ChoicheTwoForm form based on the choice made in the 'choice' field;
2. Being able to use all this data in the 'generate_pdf' view (for now what interests me is being able to include this data in the context of this view).

django form populate multiple identical field form in one submit

I don't want to use django form class as they will not give me much flexibility.
I have a form where will random number field in easy request. i am trying to populate the multiple value of forms that appears.
this is my models.py
class Profile(models.Model):
name = models.CharField(max_length=100)
photo = models.FileField()
and this my form.html
<form method="POST" action="{% url 'form' %}">
{% csrf_token %}
{% for i in range %}
<input type="text" id="name" name="name"><br>
<input type="file" id="photo" name="photo"><br><br>
{% endfor %}
<input type="submit" value="Submit">
</form>
You may notice I am rendering field with for loop.
that is means, there will be as much field as possible can be appear based on user request.
So I want to populate these models.
my view looks like
def form_view(request):
if request.method == 'POST':
# Need to puplate the form
return render(request, 'form.html', {'range': range(40)})
Can anyone please help me how can i achieve this? i am just struggling to achieve this.
you can use modelformset_factory for this. this way,
in your views.py
from .models import Profile
from django.forms import modelformset_factory
def form_view(request):
form_range = 40 # set the range here
ProfileFormSet = modelformset_factory(Profile, fields=("name", "photo"), extra=form_range, max_num=form_range)
formset = ProfileFormSet(request.POST or None)
if request.method == "POST":
if formset.is_valid():
formset.save()
return render(request, "form.html", {"profile_formset": formset})
and in your form html
<form method="POST" action="{% url 'form' %}">
{% csrf_token %}
{{ profile_formset.as_p }}
<input type="submit" value="Submit">
</form>

Modify one form instance in a Django formset?

I have a Django formset in which I render four instances of a form. Each form in the formset has two fields, but I want the last (4th) instance to only show/input one field. How can I do this, or is there a better way? I tried limiting the formset to three fields and making the fourth instance its own form, but I need to validate that field1 against the field1 fields in the formset. I couldn't see how to validate a form against a simultaneously submitted formset.
views.py:
FormSet = formset_factory(MyForm, formset=BaseMyFormSet, extra=4)
.html:
<form action="" method="post">{% csrf_token %}
{{ formset.management_form }}
{{ formset.non_form_errors }}
<div>
{% for form in formset %}
{% for field in form %}
{{ field.errors }}
{{ field.label_tag }}: {{ field }}
{% endfor %}
{% endfor %}
</div>
<p><input type="submit" value="Submit" /></p>
</form>
The formset has two fields in forms.py:
class MyForm(forms.Form):
# field1
# field2
How do I make it so the first three forms in the formset have two fields, but the last only contains field1?
Try explicitly removing the field for the last form in your views.py:
def view_func(request):
FormSet = formset_factory(MyForm, formset=BaseMyFormSet, extra=4)
if request.method == 'POST':
formset = FormSet(request.POST, request.FILES)
# assuming this is a required field for the other forms
formset.forms[-1].fields['field2'].required = False
if formset.is_valid():
...
else:
formset = FormSet()
del formset.forms[-1].fields['field2']
return render(request, 'form.html', {'formset': formset})
Any further adjustments depend on your form and validation logic. BaseMyFormSet.clean() is the appropriate place for formset-wide validation and it sounds like you already have code there to compare field1 across forms.
(From a purist sense, it might be better to have the FormSet class handle this entirely, but this is easier. FormSet code is decently complex. It'd make sense to override BaseFormSet.forms() but with that #cached_property bit, you're involved with implementation details best left to Django.)

Edit a Key/Value Parameters list Formset

I'm looking for a convenient solution to create an 'edit settings' key/values page.
Parameters model :
class Parameter(models.Model):
key = models.CharField(max_length=50)
value = models.CharField(max_length=250)
showInUI = models.SmallIntegerField()
Initial Keys/Values are already inserted in table.
I load them and send them using a model formset factory using these lines :
ParameterFormSet = modelformset_factory(Parameter, extra=0, fields=('key', 'value'))
parameterFormSet = ParameterFormSet(queryset=Parameter.objects.filter(showInUI=1))
return render_to_response('config.html', {'parameterFormSet': parameterFormSet}, context_instance=RequestContext(request))
Template side, when formset is displayed, keys and values are shown as inputs.
I'd like to find a convenient way to display form keys as readonly labels and values as inputs. And, when submited, validate them according django standards.
I've read a lot of stuff, I guess the solution may be a custom widget, but I could find a reliable solution.
Thanks for reading.
EDIT :
Working solution
views.py
def config(request):
ParameterFormSet = modelformset_factory(Parameter, extra=0, fields=('value',))
if request.method == "POST":
try:
formset = ParameterFormSet(request.POST, request.FILES)
except ValidationError:
formset = None
return HttpResponse("ko")
if formset.is_valid():
formset.save()
return HttpResponse("ok")
#ParameterFormSet = modelformset_factory(Parameter, extra=0, fields=('value',))
parameterFormSet = ParameterFormSet(queryset=Parameter.objects.filter(showInUI=1))
return render_to_response('config.html', {'parameterFormSet': parameterFormSet}, context_instance=RequestContext(request))
template
<form method="post">
{% csrf_token %}
{{ parameterFormSet.management_form }}
{% for form in parameterFormSet %}
<div>
{{ form.instance.key }}
{{ form }}
</div>
{% endfor %}
<input type="submit" />
</form>
If you do not want the value to be editable, don't include it in fields when creating the form set.
ParameterFormSet = modelformset_factory(Parameter, extra=0, fields=('value',)) # don't forget the trailing comma after 'value' otherwise it's not a tuple!
In your template, you can then loop through the forms in the form set, and display the key at the same time.
{% for form in parameter_form_set %}
{{ form.instance.key }}{# display the key related to this form #}
{{ form }}{# display the form #}
{% endfor %}

Django Inline Formset Custom Validation only Validates Single Formset at a time

I'm using Django and have a form with two additional inline formsets. I want to validate that each formset contains at least one populated form. I've written code such that this works but it only works for each formset at a time. If I submit the form without any formset forms populated, only the first one shows a validation error. If I then populate the first formset form, and leave the second one blank, the second one errors.
I want errors to appear on both forms if both are not valid.
The forms are just standard ModelForm instances. Here's my view:
class RequiredBaseInlineFormSet(BaseInlineFormSet):
def clean(self):
self.validate_unique()
if any(self.errors):
return
if not self.forms[0].has_changed():
raise forms.ValidationError("At least one %s is required" % self.model._meta.verbose_name)
def create(request):
profile_form = ProfileForm(request.POST or None)
EmailFormSet = inlineformset_factory(Profile, Email, formset=RequiredBaseInlineFormSet, max_num=5, extra=5, can_delete=False)
email_formset = EmailFormSet(request.POST or None)
PhoneFormSet = inlineformset_factory(Profile, Phone, formset=RequiredBaseInlineFormSet, max_num=5, extra=5, can_delete=False)
phone_formset = PhoneFormSet(request.POST or None)
if profile_form.is_valid() and email_formset.is_valid() and phone_formset.is_valid():
profile = profile_form.save()
emails = email_formset.save(commit=False)
for email in emails:
email.profile = profile
email.save()
phones = phone_formset.save(commit=False)
for phone in phones:
phone.profile = profile
phone.save()
messages.add_message(request, messages.INFO, 'Profile successfully saved')
return render_to_response(
'add.html', {
'profile_form': profile_form,
'email_formset': email_formset,
'phone_formset': phone_formset
}, context_instance = RequestContext(request)
)
And here's my template's form, incase it's useful:
<form action="" method="post" accept-charset="utf-8">
{{ email_formset.management_form }}
{{ phone_formset.management_form }}
{{ profile_form|as_uni_form }}
<div class="formset-group" id="email_formset">
{{ email_formset.non_form_errors }}
{% for email_form in email_formset.forms %}
<div class='form'>
{{ email_form|as_uni_form }}
</div>
{% endfor %}
</div>
<div class="formset-group" id="phone_formset">
{{ phone_formset.non_form_errors }}
{% for phone_form in phone_formset.forms %}
<div class='form'>
{{ phone_form|as_uni_form }}
</div>
{% endfor %}
</div>
<input type="submit" value="Save Profile" id="submit">
</form>
call the is_valid() function for each form that you want validation to occur on. In your example you do if a.is_valid and b.is_valid anc c.is_valid... If a is false, b and c will never get called. Try something different, like:
alpha=a.is_valid()
beta=b.is_valid()
gamma=c.is_valid()
if alpha and beta and gamma:
do stuff
I had a similar issue and the problem was that extra forms were not being validated due to how Django handles extra form fields. Take a look: Django Formset.is_valid() failing for extra forms