对于一个小应用程序,我定义了两个模型:
class Pressure (models.Model):
user = models.ForeignKey(User)
sys = models.FloatField(blank=False, null=False, verbose_name=_(u"systolic"))
dia = models.FloatField(blank=False, null=False, verbose_name=_(u"diastolic"))
pulse = models.IntegerField(blank=False, null=False, verbose_name=_(u"Pulse"))
timestamp = models.DateTimeField(verbose_name=_(u"Messurement timestamp"))
def __unicode__(self):
return self.timestamp.strftime("%y-%m-%d: %H-%M")
class Weight(models.Model):
user = models.ForeignKey(User)
weight = models.FloatField(blank=False, null=False, verbose_name=_(u"Weight"))
timestamp = models.DateTimeField(verbose_name=_(u"Messurement timestamp"))
def __unicode__(self):
return self.timestamp.strftime("%y-%m-%d: %H-%M")
不,我想为这两个模型构建一个合并表单,其中两个模型的用户和时间戳都是相同的。其余的文件应该是可选的。这意味着,如果未给出重量,则不得插入数据库等。
我在读Mixin和一些表格,但是有个好主意。这里最好的方法是什么?
最佳答案
你不需要一个表格来处理这个问题。您只需要一个视图来处理两个模型的表单。基本思想很简单:创建两个表单类,并将它们呈现给在同一<form>
元素中呈现的用户。提交时,请检查两个表单是否有效,然后在它们都有效时保存它们,并将用户发送到下一页。它看起来像这样:
from django import forms
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from django.utils.timezone import now
from .models import Pressure, Weight
class PressureForm(forms.ModelForm):
class Meta:
model = Pressure
exclude = ('user', 'timestamp', )
class WeightForm(forms.ModelForm):
class Meta:
model = Weight
exclude = ('user', 'timestamp', )
@login_required
def submit(request):
if request.method == 'POST'
pressure_form = PressureForm(request.POST)
weight_form = WeightForm(request.POST)
if all(form.is_valid() for form in [pressure_form, weight_form]):
record_time = now()
pressure = pressure_form.save(commit=False)
pressure.timestamp = record_time
pressure.user = request.user
pressure.save()
weight = weight_form.save(commit=False)
weight.timestamp = record_time
weight.user = request.user
weight.save()
return redirect('<insert-name-of-success-url>')
else:
pressure_form = PressureForm()
weight_form = WeightForm()
context = {
'pressure_form': pressure_form,
'weight_form': weight_form,
}
return render(request, '<insert-template-name>', context)
您不需要表单集或泛型视图来处理此问题。这是一个简单明了的观点。如果您发现自己经常重复这个模式,那么您可以创建一些视图类来处理这个问题。任何内置泛型都不会为您这样做。
关于python - 用Django 1.6从2个模型构建表单的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21364451/