【发布时间】:2018-02-19 23:11:37
【问题描述】:
我在同一个模型中有多个外键,由于某种原因,每当我在表单上点击提交时,最后一个外键都会覆盖之前输入的外键。任何人都可以看到发生了什么?
models.py
class Meal(models.Model):
"""
Three of these will be given to a study
"""
date = models.DateField(null=True, blank=True)
start_time = models.TimeField(null=True, blank=True)
stop_time = models.TimeField(null=True, blank=True)
description = models.CharField(max_length=256, null=True, blank=True)
class Meta:
verbose_name_plural = 'Meals For Studies'
def __str__(self):
return "Meal Information for CRF # " + str(self.general_info.case_report_form_number)
class MotionStudyInstance(models.Model):
# ###############ADD MEAL INFORMATION#######################
meal_one = models.ForeignKey(Meal, related_name='first_meal', on_delete=models.CASCADE, null=True, blank=True)
meal_two = models.ForeignKey(Meal, related_name='second_meal', on_delete=models.CASCADE, null=True, blank=True)
meal_three = models.ForeignKey(Meal, related_name='third_meal', on_delete=models.CASCADE, null=True, blank=True)
class Meta:
verbose_name_plural = 'Motion Studies Awaiting Validation'
def __str__(self):
return "CRF: #" + str(self.general_info.case_report_form_number)
forms.py
class MealForm(forms.ModelForm):
class Meta:
model = Meal
views.py
class MotionStudyInstanceFormView(LoginRequiredMixin, View):
def post(self, request):
if request.method == 'POST':
form = MotionStudyInstanceForm(request.POST, request.FILES)
meal_one_form = MealForm(request.POST)
meal_two_form = MealForm(request.POST)
meal_three_form = MealForm(request.POST)
if meal_one_form.is_valid() and meal_two_form.is_valid() and meal_three_form.is_valid():
meal_one = meal_one_form.save()
meal_two = meal_two_form.save()
meal_three = meal_three_form.save()
motion_study_instance_one = form.save(commit=False)
motion_study_instance_one.meal_one = meal_one
motion_study_instance_one.meal_two = meal_two
motion_study_instance_one.meal_three = meal_three
motion_study_instance_one.save()
return redirect('data:motion-studies')
else:
form = MotionStudyInstanceForm()
return render(request, self.template_name, {'form': form})
motionstudyinstance_form.html
{% extends "base.html" %}
{% load bootstrap3 %}
{% block content %}
<div class="container">
<h1>Motion Study Form</h1>
<form method="POST" enctype="multipart/form-data">
{% bootstrap_form form %}
<p>Meal One Information</p>
{% bootstrap_form meal_one_form %}
<p>Meal Two Information</p>
{% bootstrap_form meal_two_form %}
<p>Meal Three Information</p>
{% bootstrap_form meal_three_form %}
<input class="btn btn-default" type="submit" value="Submit">
</form>
</div>
{% endblock %}}
就像我说的,当我保存表格时,前两个用餐条目被覆盖,看起来像第三个的副本。我究竟做错了什么?我是 Django 新手。
【问题讨论】:
-
三种表单的request.POST不一样吗?
-
什么意思?
-
你说“前两个饭菜条目被覆盖,看起来像第三个的副本”,我认为这三个表单将始终具有相同的值,因为它们从 request.POST 收到相同的请求跨度>
-
我为每顿饭提供了单独的表格。我将如何为每个请求单独提出请求?
-
那你如何提交这些froms?逐个?。如果是这样,您可以更改每个表单的操作。如果在单个表单中呈现他们的字段数据,则可以根据 POST 数据中的字段名称确定提交哪个表单
标签: django django-models django-forms django-views foreign-keys