我正在尝试使用inlineformset来创建父模型和一些子模型。以下是我的观点。该代码用于将初始Rfq模型保存到数据库,但在尝试保存行inlineformset时出错。这是一对多关系,但是使用ForeignKey字段完成。
# views.py
def rfq_create(request):
form = RfqForm(request.POST or None)
RfqFormSet = inlineformset_factory(Rfq, Rfqlines, form=RfqlinesForm, extra=5, can_delete=True)
lines_formset = RfqFormSet(request.POST or None)
title = "Create a new RFQ"
context = {
"title": title,
"form": form,
"lines_formset": lines_formset,
}
if form.is_valid() and lines_formset.is_valid():
rfq = form.save(commit=False)
rfq.user = request.user
rfq.save()
lines_formset.save()
rfq_list = Rfq.objects.order_by('rfq_id')[:20]
title = "RFQ List"
context = {
"title": title,
"rfq_list": rfq_list
}
return render(request, "rfq.html", context)
return render(request, "rfq_create.html", context)
我已经尝试过查看官方的Django文档,但它似乎并不适用......或者说不是那么直截了当。
这是我的追溯
Environment:
Request Method: POST
Request URL: http://localhost:8000/rfq/create
Django Version: 1.8.7
Python Version: 3.4.3
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'django.forms.formsets',
'jquery',
'crispy_forms',
'registration',
'home',
'rfq',
'dashboard',
'pipeline')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "/home/brandon/employees/env/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/brandon/employees/rfq/views.py" in rfq_create
36. lines_formset.save()
File "/home/brandon/employees/env/lib/python3.4/site-packages/django/forms/models.py" in save
636. return self.save_existing_objects(commit) + self.save_new_objects(commit)
File "/home/brandon/employees/env/lib/python3.4/site-packages/django/forms/models.py" in save_new_objects
767. self.new_objects.append(self.save_new(form, commit=commit))
File "/home/brandon/employees/env/lib/python3.4/site-packages/django/forms/models.py" in save_new
900. obj.save()
File "/home/brandon/employees/env/lib/python3.4/site-packages/django/db/models/base.py" in save
685. "unsaved related object '%s'." % field.name
Exception Type: ValueError at /rfq/create
Exception Value: save() prohibited to prevent data loss due to unsaved related object 'rfq'.
答案 0 :(得分:5)
问题的答案是这个
lines_formset = RfqFormSet(request.POST or None, instance=form.instance)
form.instance是被忽视的关键。
答案 1 :(得分:2)
您需要将父模型实例传递给inline_formset。
有关详细信息,请参阅this relevant section of the Django docs。
示例:
lines_formset = RfqFormSet(request.POST, request.FILES, instance=rfq)
这是必要的,因此Django可以适当地设置子模型的ForeignKey关系。