Add and delete in one instance django Formset
I have a formset which generally works (Add, Delete, Edit) items except when I decide to Add and Delete(or vice versa) in one instance, the formset throws the 'id': ['This field is required.']
error.
Below are prints of request.POST
:
When it works:
<QueryDict: {'csrfmiddlewaretoken': ['lnEG6qbrWRg4NdkKwg1UU86KTBuIgJIc4ZqJAWvZpASgxECnicmlUmVhJIInvqEJ'], 'form-TOTAL_FORMS': ['3'], 'form-INITIAL_FORMS': ['3'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'form-0-id': ['6'], 'form-0-year': ['2023'], 'form-1-id': ['7'], 'form-1-year': ['2024'], 'form-2-id': ['8'], 'form-2-year': ['2025']}>
When it does not work (I deleted 2024 and added 2026):
<QueryDict: {'csrfmiddlewaretoken': ['fh0mPGYzVt0AOjpE5Q9JuTp1zuqwNCuMYTMpjci7ocCMyKHhRMuau7eypBEb2jqj'], 'form-TOTAL_FORMS': ['3'], 'form-INITIAL_FORMS': ['3'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'form-0-id': ['6'], 'form-0-year': ['2023'], 'form-1-id': ['8'], 'form-1-year': ['2025'], 'form-2-id': [''], 'form-2-year': ['2026']}>
[{}, {}, {'id': ['This field is required.']}]
Model:
class Year(models.Model):
year = models.CharField(max_length=100, null=True)
user = models.CharField(max_length=300, null=True, blank=True)
Forms:
YearFormset = forms.modelformset_factory(
Year,
fields=('year',),
extra=1,
widgets={
'year': forms.TextInput(
attrs={
'require': 'required',
'class': 'form-control',
'placeholder': 'Enter Year here'
})
}
)
View:
def year(request):
year_items = Year.objects.filter(user=1)
year_set = YearFormset(queryset=year_items)
year_set.extra = 0 if year_items else 1
context = {'years':year_set}
if request.method == 'POST':
print(request.POST)
submit_year = YearFormset(request.POST)
if submit_year.is_valid():
Template:
<form method="POST">
{% csrf_token %}
<br>
{{ years.management_form }}
{% for year in years %}
<div class="form-row">
<div class="col-4">
<div class="input-group">
{{year.id}}
{{year.year}}
<button class="btn btn-success add-form-row">+</button>
</div>
<br>
</div>
</div>
{% endfor %}
<input type="submit" value="Update Years">
</form>