I want to create a formset of confirmation models. I've succesfully created the formset however formset creates an extra confirmation object.
Here is my code:
VIEW
def render_fulfillment_modal(request,template='test.html'):
....
formset = modelformset_factory(Confirmation)
form = formset(queryset=Confirmation.objects.filter(customer_order__deal = deal))
if request.method == 'POST':
form = formset(request.POST, request.FILES)
if form.is_valid():
form.save()
TEMPLATE
<form method="post" action="{% url open_fullfill_modal deal.id %}">{% csrf_token %}
{{ form.management_form }}
{% for f in form %}
<tr>
<td>{{f.fullfilled}}</td>
<td>
<p class="name">{{f.instance|confirmation_user_info}}</p>
</td>
<td><input type="text" class="input-small datepicker"></td>
<td>{{f.tracking_code}}</td>
</tr>
{% endfor %}
<div class="pull-right button-box">
<button type="submit" class="btn btn-primary btn-large">Save Changes</button>
</div>
I'm getting an extra form for unrelated object which is not in my queryset. I've tried this with another models and each time I'm getting an extra object. I suppose it's something with the formsets to handle data or something, I'm not sure. The problem occurs when I post this form. It gives me MultiValueDictKeyError which is :
"Key 'form-0-id' not found in <QueryDict: {u'form-MAX_NUM_FORMS': [u''], u'form-TOTAL_FORMS': [u'3'] ...
Any ideas ?
Just put a {{f.id}} before {{f.fullfilled}}
It's given a hidden form-id for all f, and pass it to QueryDict in request.Post
As you can see from the definition of modelformset_factory below (django docs) the extra parameter defaults to 1, which creates the extra object you mentioned.
modelformset_factory(model, form=ModelForm, formfield_callback=None, formset=BaseModelFormSet, extra=1, can_delete=False, can_order=False, max_num=None, fields=None, exclude=None, widgets=None, validate_max=False, localized_fields=None, labels=None, help_texts=None, error_messages=None, min_num=None, validate_min=False, field_classes=None, absolute_max=None, can_delete_extra=True)
So all you need to pass extra=0 to the formset:
formset = modelformset_factory(Confirmation, extra=0)
From Django docs: Limiting the number of editable objects
As with regular formsets, you can use the max_num and extra parameters to modelformset_factory() to limit the number of extra forms displayed.
Related
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>
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.)
I have a formset which has some initial data provided - it's a data cloned from other model which contains 2 fields 'group' and 'requested'.
When initial data is provided the forms in formset do not get saved, they only get saved when I'll modify the form with the data a little bit.
When no initial data is provided forms do get saved.
Why adding intial data to a formset makes it impossible to save formsets data to the database?
This is my formset existing in get_context_data dictionary:
initial = ProcedureActionGroup.objects.filter(procedure__id=self.kwargs.get('pk', None))
initial_values = initial.values('group', 'requested')
print initial_values
initial_count = initial.count()
ActionGroupFormset = inlineformset_factory(self.model, TaskGroup, extra=initial_count,
form=TaskActionGroupForm,
can_delete=False,
)
data['formset'] = ActionGroupFormset(self.request.POST or None, initial=initial_values,
**self.get_formset_kwargs())
This is my form_valid method where I save all data
def form_valid(self, form):
context = self.get_context_data()
forms = []
forms.append(form.is_valid())
if self.get_procedure_obj():
formset = context['formset']
forms.append(formset.is_valid())
if all(forms):
self.object = form.save(commit=False)
form.save()
if self.get_procedure_obj():
formset = formset.save(commit=False)
for obj in formset:
obj.task = self.object
obj.save()
self.object.extract_users()
return HttpResponseRedirect(self.object.get_absolute_url())
Model:
class TaskGroup(models.Model):
task = models.ForeignKey(Task, null=True, blank=False)
group = models.ForeignKey(ActionGroup, null=True, blank=True)
requested = models.PositiveIntegerField(u'Requested', null=True, blank=True)
form template:
<form method="post" action="" class="span6 offset2 form form-horizontal">
{% crispy form%}
{{formset.management_form}}
{% if formset %}
<div>
<fieldset>
<table class="table table-striped">
{% for form in formset%}
<tr>
{% for field in form %}
<td> {{field}} </td>
{% endfor %}
</tr>
{% endfor %}
</table>
</fieldset>
</div>
{% endif %}
<div class="form-actions">
<button class="btn btn-primary btn-large" type="submit">
Save
</button>
</div>
</form>
I had a similar issue using django extra views.
I solved it bay modifying the form class that is passed to the inlineformset_factory. the ModelForm.has_changed method was returning false.
class TaskActionGroupForm(ModelForm):
model = YourModel
def has_changed(self):
"""
Overriding this, as the initial data passed to the form does not get noticed,
and so does not get saved, unless it actually changes
"""
changed_data = super(ModelForm, self).has_changed()
return bool(self.initial or changed_data)
In exmaple above I used inlineformset_factory which treaded values passed to initial as already existing objects.
So when I looped over my formset with:
for form in formset:
form.has_changed()
form.has_changed() returned False
I've repleaced inlineformset_factory to formset_factory which treats intial data as new data which get's saved correctly. Code example will be posted tomorrow.
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
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(): ...