Dynamically populating fields in a form set

I have two models that look like this:

class RouteBase(models.Model):
    base        =   models.ForeignKey("Base")
    route       =   models.ForeignKey("Route")
    sequence    =   models.IntegerField()

class Route(models.Model):
    bases       =   models.ManyToManyField("Base", through="RouteBase", blank=True)
    description =   models.TextField(blank=True)
    #and a few other attributes omitted for brevity

... then a model form that looks like this:

class RouteBaseForm(ModelForm):
    base = forms.ModelChoiceField(queryset=Base.objects.all(), widget=forms.TextInput)
    sequence = forms.IntegerField(widget=forms.HiddenInput)

    class Meta:
        model = RouteBase

As you can see, the sequence widget is hidden, since I want this field to be automatically processed by django. I want the user to just enter the base through the text box. The sequence is displayed in the order of the text fields.

I created a form with this form to create / edit all the bases in the route:

RouteBaseFormset = inlineformset_factory(Route, RouteBase, form=RouteBaseForm, extra=5, )

When this form set is created, the sequence field is empty. I need to fill it with values ​​before I save the set of forms (otherwise it will not be validated). I can come up with about 4 ways to do this.

  • Before submitting the form template to the template, I ran this code:
    i = 1
    for form in formset.forms:
        form.fields["sequence"].initial = i
        i += 1

, . , 5 , , . , 2 3 . , "base" . , formet POSTED, , , , , , ...

  1. , POSTED , , , , , . , .save() , , . , , .save(commit=False), , . ...

  2. , request.POST , .

  3. blank=True RouteBase, .

, ?

+3
2

, , , .

commit = False .

+5
newPOST = request.POST.copy()
i=1
for index in range(0, int(request.POST["routebase_set-TOTAL_FORMS"])-1):
    if request.POST["routebase_set-" + str(index) + "-base"]:
        newPOST["routebase_set-" + str(index) + "-sequence"] = i
        i += 1
    else:
        newPOST["routebase_set-" + str(index) + "-sequence"] = ""

, , , . , , ...

-2

Source: https://habr.com/ru/post/1710884/


All Articles