user2167177
user2167177

Reputation:

Dynamic Forms with Foreign Keys in Django

I have the following models

class Make(models.Model):
    make_name = models.CharField(max_length=32)
    def __unicode__(self):
        return self.book_title

class MakeModel(models.Model):
    model_number = models.IntegerField()
    model_capacity = models.IntegerField()
    model_capacity_unit = models.CharField(max_length=4)
    Make = models.ForeignKey(Make)
    def __unicode__(self):
            return self.model_number

Basically, I want my form to have all the Make details at the top, and all the MakeModel details in a grid below, and to be able to add more MakeModels with ease. Such as in this mockup

https://www.dropbox.com/s/e7rg3zxe6y8q9fi/invoicedetails.gif

Any ideas what needs doing? People mention things like inlineformset_factory, but I'm not convinced either how to use it, or if it will do the thing I expect.

Any help would be appreciated

Upvotes: 0

Views: 469

Answers (1)

You need a form and a formset.

  • A form: one form
  • A formset: multiple copies of one form

Your view would look something like this in the POST cycle:

Update: oh right, foreignkey. The easiest way to be honest is just to commit=False the formset and manually assign the FK. You can use an inlineformset as well. https://docs.djangoproject.com/en/dev/ref/forms/models/#django.forms.models.inlineformset_factory

FormSet = modelformset_factory(MakeModel)
Form = modelform_factory(Make)

def myview(request):
    formset = FormSet(request.POST or None)
    form = Form(request.POST or None)

    if request.method == 'POST':               
        if formset.is_valid() and form.is_valid():
           main_instance = form.save()
           formset.save(commit=False)
           for instance in formset:
               instance.fk = main_instance
               instance.save()

https://docs.djangoproject.com/en/dev/topics/forms/formsets/

Upvotes: 2

Related Questions