Django将一种模型的多种形式的数据添加到数据库

时间:2019-01-20 02:46:10

标签: django django-models django-forms django-views multiple-forms

我有一个模型Measurement,有两种形式MeassurementSystolicPressureForm和MeassurementDiastolicPressureForm。我想做一个允许用户将它们都添加到数据库的视图。每个都有字段:用户名,measurement_date,值,measurement_type。当我在网页上填写表格时,会将两个记录添加到数据库中,每个记录都具有良好的用户名和Measurement_type,但是两个记录的Measurement_date和value相同。您能帮我发现我在做什么错吗?

这是我的代码:

models.py

class Measurement(models.Model):
    value = models.IntegerField()
    measurement_type = models.CharField(max_length=6, default='measurement', blank=True)
    username = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    measurement_date = models.DateTimeField(default=datetime.now, editable=True)

forms.py

class MeassurementSystolicPressureForm(ModelForm):
    class Meta:
        model = Measurement
        fields = ['value',  'measurement_date']


class MeassurementDiastolicPressureForm(ModelForm):
    class Meta:
        model = Measurement
        fields = ['value', 'measurement_date']

views.py

def new_measurement(request):
    if request.method == 'POST':
        form_SP = MeassurementSystolicPressureForm(request.POST or None)
        form_DP = MeassurementDiastolicPressureForm(request.POST or None)
        if form_CS.is_valid() or form_CR.is_valid():

            temp_S = form_SP.save(commit=False)
            temp_S.username = request.user
            temp_S.measurement_type = 'syspres'
            temp_S.save()

            temp_D = form_DP.save(commit=False)
            temp_D.username = request.user
            temp_D.measurement_type = 'diapres'
            temp_D.save()

            return redirect('/')
    else:
        form_SP = MeassurementSystolicPressureForm()
        form_DP = MeassurementDiastolicPressureForm()
        args = {'form_SP': form_SP, 'form_DP': form_DP}
        return render(request, 'measurements.html', args)

例如,如果我提交以下数据:

Systolic Pressure:
value: 120 
date: 2019-01-15 16:15:32
Diastolic Pressure:
value: 80
date: 2019-01-15 15:00:00`

在我的数据库中,我有两条记录:

username: Julka, measurement_type: 
syspres, value: 80, date: 2019-01-15 15:00:00
username: Julka, measurement_type: diapres, value: 80, date: 2019-01-15 15:00:00

我不知道该怎么办。

2 个答案:

答案 0 :(得分:0)

在HttpRequest对象中,GET和POST属性是django.http.QueryDict的实例。仅此类型无法确定提交的表单。您的表单具有相同的字段,因此一种表单有效,另一种表单也有效。这就是为什么两个记录的Measurement_date和value都相同的原因。要解决此问题,您可以在表单中添加其他隐藏字段,并查看从中发送表单的字段。像这样:

class MeassurementSystolicPressureForm(ModelForm):
    flag_Systolic = forms.IntegerField()
    class Meta:
        model = Measurement
        fields = ['value',  'measurement_date']
    def __init__(self, *args, **kwargs):
        super(MeassurementSystolicPressureForm, self).__init__(*args, **kwargs)
        self.fields['flag_Systolic'].widget = forms.HiddenInput()


class MeassurementDiastolicPressureForm(ModelForm):
    flag_Diastolic = forms.IntegerField()
    class Meta:
        model = Measurement
        fields = ['value', 'measurement_date']
    def __init__(self, *args, **kwargs):
        super(MeassurementDiastolicPressureForm, self).__init__(*args, **kwargs)
        self.fields['flag_Diastolic'].widget = forms.HiddenInput()

并在您看来:

def new_measurement(request):
    if request.method == 'POST':
        if 'flag_Systolic' in request.POST:
            form_SP = MeassurementSystolicPressureForm(request.POST)
            if form_SP.is_valid():
                temp_S = form_SP.save(commit=False)
                temp_S.username = request.user
                temp_S.measurement_type = 'syspres'
                temp_S.save()
                return redirect('/')
        elif 'flag_Diastolic' in request.POST:
            form_DP = MeassurementDiastolicPressureForm(request.POST)
            if form_DP.is_valid():
                temp_D = form_DP.save(commit=False)
                temp_D.username = request.user
                temp_D.measurement_type = 'diapres'
                temp_D.save()
                return redirect('/')
    else:
        form_SP = MeassurementSystolicPressureForm()
        form_DP = MeassurementDiastolicPressureForm()
        args = {'form_SP': form_SP, 'form_DP': form_DP}
        return render(request, 'measurements.html', args)

答案 1 :(得分:0)

我知道可能为时已晚,但这可能对其他面临相同问题的人有所帮助。

一个更简单的解决方案是在View中创建对象并将其传递给两种形式:

from .models import Measurement
def new_measurement(request):
    user=request.user                       #the authenticated user
    if request.method == 'POST':
        measurement=Measurement(username=user)
        form_SP = MeassurementSystolicPressureForm(request.POST or None, instance=measurement)
        form_DP = MeassurementDiastolicPressureForm(request.POST or None, instance=measurement)
        if form_CS.is_valid() or form_CR.is_valid():
            form_CS.save()
            form_CR.save()
            return redirect('/')
    else:
        form_SP = MeassurementSystolicPressureForm()
        form_DP = MeassurementDiastolicPressureForm()
        args = {'form_SP': form_SP, 'form_DP': form_DP}
        return render(request, 'measurements.html', args)