Mirko Brombin
Mirko Brombin

Reputation: 1012

Django - CreateView with multiple models

Can I use Django CreateViews to make a form that add data to multiple tables? I've created a model called UserMeta to store some additional informations of my users.

The Problem

I want to create a view with CreateViews, that display fields for creating a new user (Django User Model) and some extra fields based on my UserMeta model:

class UserMeta(models.Model):
    country_code = models.CharField(max_length=30, verbose_name="Nome",
                            help_text="Insert the name of the country")

I need an output schema like this:

|-form

|-- input user.name

|-- input user.username

|-- input user....

|-- input usermeta.country_code

Upvotes: 8

Views: 7368

Answers (1)

Ian Price
Ian Price

Reputation: 7626

You can use django-extra-views, a collection of additional CBVs, for this purpose.

from extra_views import CreateWithInlinesView InlineFormSet

class UserMetaInline(InlineFormSet):
    model = UserMeta    

class UpdateOrderView(CreateWithInlinesView):
    model = User
    inlines = [UserMetaInline,]

While these inlines are generally used for foreign key relations, they work for one-to-one as well.

Upvotes: 9

Related Questions