S
S
sazhyk2016-12-02 13:08:05
Django
sazhyk, 2016-12-02 13:08:05

How to create a form from two related models in Django?

There are two models
models.py

from django.db import models

class Person(models.Model):
    name = models.CharField()

class Phone(models.Model):
    person = models.ForeignKey(Person)
    number = models.CharField()

From them two forms
forms.py
from django import forms
from myapp.models import Person, Phone

class PersonForm(forms.ModelForm):
    class Meta:
        model = Person
        fields = ('name')

class PhoneForm(forms.ModelForm):
    class Meta:
        model = Phone
        fields = ('number')

View views.py
from django.shortcuts import render, HttpResponseRedirect
from myapp.forms import PersomForm, PhomeForm

def new_person(request):
    if request.method == "POST":
        person_form = PersonForm(request.POST or None)
        phone_form = PhoneForm(request.POST or None)
        if person_form.is_valid() and phone_form.is_valid():
            person_f = person_form.save(commit=False)
            person_f.author = request.user
            phone_f = phone_form.save(commit=False)
            ???
            phone_form.save()
            person_form.save()
            person_form.save_m2m()
            return HttpResponseRedirect('/person/new/')
    else:
        person_form = PersonForm()
        phone_form = PhoneForm()
    context = {
        'person_form': person_form,
        'phone_form': phone_form,
    }
    return render(request, 'form.html', context)

And template
form.html
<form method="post" action="" class="form-horizontal">
    {% csrf_token %}
    {{ person_form  }}
    {{ phone_form  }}
    <input type="submit" value="Создать" />
</form>

Why am I getting the error
The above exception (ОШИБКА: нулевое значение в столбце "person_id" нарушает ограничение NOT NULL DETAIL: Ошибочная строка содержит (1, +7(900)123-45-67, null). ) was the direct cause of the following exception:

Actually a question. I understand what's wrong, I can't get person_id. Therefore, in my view, there are question marks where there should be a receipt of it. If you do not do it phone_f = phone_form.save(commit=False), but immediately save it, you still get the same error.
CHADNT?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artyom Bryukhanov, 2016-12-02
@drupa

djbook.ru/rel1.9/topics/forms/modelforms.html#inli...
I think this is the solution to your problem

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question