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)
... 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, , , , , , ...
, POSTED , , , , , . , .save() , , . , , .save(commit=False), , . ...
, request.POST , .
blank=True RouteBase, .
, ?