Answer the question
In order to leave comments, you need to log in
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 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')
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)
<form method="post" action="" class="form-horizontal">
{% csrf_token %}
{{ person_form }}
{{ phone_form }}
<input type="submit" value="Создать" />
</form>
The above exception (ОШИБКА: нулевое значение в столбце "person_id" нарушает ограничение NOT NULL DETAIL: Ошибочная строка содержит (1, +7(900)123-45-67, null). ) was the direct cause of the following exception:
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. Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question