Saving changes in FormSet with related models

Question:

Business logic:
Two employees.
First employee create application with input ‘type_car’.
Second employee update application input ‘reg_mark’ and ‘brand’.

So, on first step i can create application. I have for this ‘type_car’ select input field with good view, because it get elements from model with str method.

But, i can’t update application on second step. If i select ‘reg_mark’ and try save my changes, i get initial application with empty field ‘reg_mark’.

And additional, for application i get object from model ‘Car’ with str method ‘reg_mark’ and it identically show in select fields ‘brand’ and ‘reg_mark’. How i can fix it?

Models:

class Application(models.Model):
    reg_mark = models.ForeignKey(Car, ... )
    brand = models.ForeignKey(Car, ... )
    type_car = models.ForeignKey(TypeCar, ... )


class Car(models.Model):
    brand = models.CharField(max_length=50)
    reg_mark = models.CharField(max_length=10)
    type = models.ForeignKey('TypeCar', ... )

    def __str__(self):
        return self.reg_mark



class TypeCar(models.Model):
    title = models.CharField(max_length=20)

    def __str__(self):
        return self.title

I’ using two identically FormSets for input (Add and Close)

class ApplicationCloseForm(forms.ModelForm):
    class Meta:
        model = Application
        fields = {
            'reg_mark',
            'brand',
            'type_car',
        }

ApplicationCloseFormSet = modelformset_factory(
    Application,
    form=ApplicationCloseForm,
    extra=0,
    can_delete=False,
)

view for create application

def application_add(request):
    if request.method == 'POST':
        formset = ApplicationAddFormSet(request.POST or None)
        if formset.is_valid():
            formset.save()

    else:
        formset = ApplicationAddFormSet(queryset=Application.objects.none())

    return render(request, 'applications/application_add.html', {'formset': formset})

view for update application

def applications_list(request):
    applications = Application.objects.all()

    if request.method == 'POST':
        formset = ApplicationCloseFormSet(request.POST or None)
        if formset.is_valid():
            formset = formset.save(commit=False)
            formset.save()

    formset = ApplicationCloseFormSet(queryset=applications)

    return render(request, 'applications/applications_list.html', {'formset': formset})
Asked By: epatage

||

Answers:

Everything is simple. I forgot to add the tag {{ formset.management_form }} to the template (or need use tag {{ form.id }} in the loop {% for form in formset %}). So my changed data wasn’t valid.

Answered By: epatage
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.