Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - CreateView with multiple models

Tags:

python

django

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

like image 789
Mirko Brombin Avatar asked Feb 22 '16 18:02

Mirko Brombin


1 Answers

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.

like image 98
Ian Price Avatar answered Nov 10 '22 08:11

Ian Price