Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is instance= in Django?

Tags:

python

django

I have the following code:

def addbook(request):
    form = AuthorForm()
    book_formset = BookFormset(instance=Author())

I know that BookFormset is an inline formset and that Author is an object.

Why is Author part of (instance=); what does it mean and what does it do?

like image 736
knothirsty Avatar asked Aug 31 '25 06:08

knothirsty


1 Answers

As the documentation states, the instance keyword argument is passed the model whose relations that the formset will edit.

If you want to create a formset that allows you to edit books belonging to a particular author, you could do this:

>>> from django.forms.models import inlineformset_factory
>>> BookFormSet = inlineformset_factory(Author, Book, fields=('title',))
>>> author = Author.objects.get(name='Mike Royko')
>>> formset = BookFormSet(instance=author)
like image 166
Ignacio Vazquez-Abrams Avatar answered Sep 02 '25 19:09

Ignacio Vazquez-Abrams