使用modelchoicefield时,Django表单无效

时间:2016-11-08 13:54:43

标签: django forms

我是Django的新手,我一直在努力在我的观点中获得forms.ModelChoiceField的选定值。我的表单(post)无效,我注意到request.POST返回ModelChoiceField中的所有可能值。如何仅获取用户选择的模型?提前感谢您的帮助。

模型

我有传感器模型以及测量模型......

class Sensor(models.Model):
    # This contains information about a sensor, type, location, and other
    type = models.CharField(max_length=16)
    ...

class Measurement(models.Model):
    #This contains the measurements of the sensors at a given date
    sensor = models.ForeignKey('Sensor')
    date = models.DateField()
    temperature = models.FloatField()
    pressure = models.FloatField()
    ...
    class Meta:
        unique_together = ('sensor', 'date')

表格

...以及允许用户选择传感器和日期的表单:

class MeasurementForm(forms.ModelForm):
    #the user is allowed to choose any sensor that is related to the measurement table
    sensor = forms.ModelChoiceField(queryset=Sensor.objects.exclude(measurement=None))
    date =  forms.DateField(widget=DateInput(attrs={'format':'%Y-%m-%d'}), initial=datetime.today)

到目前为止一切都很好,这由get方法呈现,用户可以选择传感器和日期。但是,在提交后,以下视图在帖子中失败:

视图

class MeasurementView(View):
    form_class = MeasurementForm
    my_template = "measurement.html"

    def get(self, request, *args, **kwargs):
        form = self.form_class()
        return render(request, self.my_template, {'form': form, 'data':None})

    def post(self, request, *args, **kwargs):
        print(request.POST)
        print(new_form.errors)
        new_form = self.form_class(data=request.POST)
        if new_form.is_valid():
            print('form is valid')
            data = get_data_for_sensor_date(
                        new_form.cleaned_data['sensor'],
                        new_form.cleaned_data['date']))
            return render(request, self.my_template, {'form':new_form, 'data':data})
        else:
            return render(request, self.my_template, {'form':new_form, 'data':None})

控制台输出

<QueryDict: {'sensor': ['', '1'], 
             'csrfmiddlewaretoken': ['YUPfrdhdbQdAa7EyNx2sJeHdbxmQXTTW'], 
             'date': ['2016-11-07']}>

<ul class="errorlist">
  <li>__all__
    <ul class="errorlist nonfield">
      <li>Measurement with this Sensor and Date already exists.
      </li>
    </ul>
  </li>
</ul>

1 个答案:

答案 0 :(得分:0)

我找到了这个链接Django formview returns object already exists error with a modelform

我引用的是: &#34;正常。我找到了一个解决我错误的方法。是什么导致模型已经存在错误是我的ModelForm CheckProductForm。 Codename属性是唯一的,因此我的验证总是返回False。我所做的是将我的原始ModelForm更改为Form。这解决了我的整个问题。对于form_valid问题中的form_invalid。如果产品不存在,我已覆盖我的表单的clean_codename函数以引发ValidationError。&#34;

我仍然不明白为什么我首先出现错误。但是,将表单更改为下面的代码就成了诀窍。

<强>表格

class MeasurementForm(forms.Form):
    #the user is allowed to choose any sensor that is related to the measurement table
    sensor = forms.ModelChoiceField(queryset=Sensor.objects.exclude(measurement=None))
    date =  forms.DateField(widget=DateInput(attrs={'format':'%Y-%m-%d'}), initial=datetime.today)