Get newly added forms from django formset

124 views Asked by At

I have a formset as follows:

TableAddFormSet = modelformset_factory(Table, form=TableAddForm)

The model looks like this:

class Table(models.Model):

    restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
    amount_of_people = models.IntegerField()
    category = models.CharField(max_length=10)
    reserved = models.BooleanField(default=False)

Now the model required the attribute 'restaurant', which I will set on form-submission. Until now I've done the following:

for form in formset:
    form.instance.restaurant = request.user.restaurant

which means that even forms that already existed get looped through and updated. Is there a more efficient way to add this attribute to the newly added forms, something like:

for form in formset.new_forms():

or is my implementation the most suitable way for solving this problem?

1

There are 1 answers

0
Tim Tisdall On

You should be able to use inlineformset_factory like this:

TableAddFormSet = inlineformset_factory(Restaurant, Table, form=TableAddForm)
table_formset = TableAddFormSet(request.POST or None, instance=request.user.restaurant)

As the name implies, it's more intended for when you create a form that has a formset within it (so, a "restaurant" form that has multiple "table" entries within it), but it should work fine for what you're doing too.