0

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.

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

This is not the right way to implement what you are trying to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.