Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - combining forms for related models

Tags:

django-forms

Is there a common method/best practice/any means for combining forms that span multiple related models?

I want to create/edit model objects along with other, related model objects on the same page. Basically, being able to create/edit one model instance and another set of model instances related by a foreign key.

Not a great explanation, I know.

class Person(models.Model):
    name = models.CharField(max_length=64, unique=True)

class PhoneNumber(models.Model):
    person = models.ForeignKey(Person)
    description = models.CharField(max_length=64, blank=True, null=True) 
    number = models.CharField(max_length=32, blank=True, null=True)

I want to be able to create/edit a person, along with all their associated phone numbers using a single form/page.

I've done this before using this nested form example, but it seems quite hackish.

like image 645
Emma Avatar asked Jul 13 '11 02:07

Emma


People also ask

How do I link models and forms in Django?

models import User class InputUserInfo(forms. Form): phone = forms. CharField(max_length=20) instagram = forms. CharField(max_length=20) facebook = forms.

Why use ModelForm in Django?

Django Model FormIt is an efficient way to create a form without writing HTML code. Django automatically does it for us to reduce the application development time. For example, suppose we have a model containing various fields, we don't need to repeat the fields in the form file.

What is formset in Django?

A formset is a layer of abstraction to work with multiple forms on the same page. It can be best compared to a data grid. Let's say you have the following form: >>> from django import forms >>> class ArticleForm(forms.


1 Answers

Yes! Use formsets, specifically https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets

like image 163
Issac Kelly Avatar answered Oct 18 '22 20:10

Issac Kelly