Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Inline Formsets using custom form

I am using inline formsets.

My model:

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

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

class AuthorForm(ModelForm):
    class Meta:
        widgets = {
            'description': Textarea(attrs={'cols': 40, 'rows': 4}),
        }

In my views.py I made the form from the AuthorForm like so

form = AuthorForm(request.POST)

But I also made a formset for the Books

InlineFormSet = inlineformset_factory(Author, Books)

I cannot pass in a BooksForm with widgets, so how do I add a textarea widget to the book details.

Is it even possible? Am I missing something obvious?

like image 716
Mark Avatar asked Feb 24 '11 14:02

Mark


1 Answers

Try:

class BookForm(ModelForm):
    class Meta:
        model = Book
        widgets = {
            'details': Textarea(attrs={'cols': 40, 'rows': 4}),
        }


InlineFormSet = inlineformset_factory(Author, Book, form=BookForm)

Update by Wtower

This is great. Specifically for widgets, as of Django 1.6 there is a widgets parameter for inlineformset_factory

Sounds like you can now call

inlineformset_factory(Author, Book, widgets={'details': Textarea(attrs={'cols': 40}))
like image 83
Yuji 'Tomita' Tomita Avatar answered Sep 24 '22 06:09

Yuji 'Tomita' Tomita