raphael
raphael

Reputation: 447

Pass model instance to django form

I have model A and model B. Thusly:

class A(models.Model):
     ...

class B(models.Model):
    a = models.ForeignKey(A)
    ...

Now, a user makes an instance of model A, and from the detail page I want to allow them to click a link to create instances of model B that's attached to the A they just made. Is there an easy way for me to pass to the form for model B what instance of model A (the one the user is looking at) I want to attach it to? There is no reason for the user to know anything about it, and making a hidden field seems to be a bit of a hack, as does putting it as a get variable. Just wondering if there is a smoother way to go about it.

Upvotes: 0

Views: 5353

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174624

Now, a user makes an instance of model A, and from the detail page I want to allow them to click a link to create instances of model B that's attached to the A they just made.

You are looking for inline formsets:

Inline formsets is a small abstraction layer on top of model formsets. These simplify the case of working with related objects via a foreign key.

The example from the documentation explains it better than I could:

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    author = models.ForeignKey(Author)
    title = models.CharField(max_length=100)

from django.forms.models import inlineformset_factory
BookFormSet = inlineformset_factory(Author, Book)
author = Author.objects.get(name=u'Mike Royko')
formset = BookFormSet(instance=author)

Upvotes: 2

catavaran
catavaran

Reputation: 45565

Passing such field as a hidden is a normal solution.

class BForm(forms.ModelForm):
    class Meta:
        model = B
        widgets = {'a': forms.HiddenInput()}

And in views.py initiate this field with instance of A:

form = BForm(initial={'a': a})

This is not a hack but standard option.

Upvotes: 1

Related Questions