ModelForm因缺少值而无法验证,但模型字段为null = True

时间:2016-09-07 11:59:21

标签: python django

我的ModelForm尝试将''分配给某个字段时出现问题(如果我实际提供了Product的主键,则会保存正常,但是{&#39}不是必填字段,如果字段留空,则不会保存。)我认为ORM正试图将该字段设置为'',但是:

  • 不应该''被强迫None,并且;
  • 为什么模型表单首先尝试将该字段设置为None而不是 ''

models.py

class Question(models.model):
    fk_product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, related_name="product_question")

forms.py

class QuestionForm(forms.ModelForm):
    fk_product=forms.ChoiceField(required=False)
    class Meta:
        model = Question
        fields = ['fk_product',]

错误:

  

无法指定"''":" Question.fk_product"必须是"产品"   实例

产生错误的视图代码:

    QuestionModelFormset = modelformset_factory(Question,
                                form=QuestionForm,
                                extra=1)
    question_formset = QuestionModelFormset(
                            data=request.POST,
                            files=request.FILES,
                            queryset=Question.objects.all())
    if not question_formset.is_valid(): #error occurs on this line

1 个答案:

答案 0 :(得分:4)

尝试添加private void button2_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(_txtBoxMsg.Text)) { try { Byte[] data = System.Text.Encoding.ASCII.GetBytes(_txtBoxMsg.Text); stream = client.GetStream(); // Send the message to the connected TcpServer. stream.Write(data, 0, data.Length); Debug.WriteLine("DDB Client Message: " + _txtBoxMsg.Text); data = new Byte[1024]; String responseData = String.Empty; Int32 bytes = stream.Read(data, 0, data.Length); responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes); Debug.WriteLine("DDB Client recieved: " + responseData); lbMsgs.Items.Add(string.Format("Received: {0}", responseData)); } catch (ArgumentNullException ex) { MessageBox.Show("ArgumentNullException: " + ex); ; } catch (SocketException ex) { MessageBox.Show("SocketException: " + ex); } } else MessageBox.Show("You did not enter a message to be sent to server!", "Please enter a message", MessageBoxButtons.OK); }

blank=True表示该字段在数据库中允许为NULL。

null=True表示可以在表单中没有值的情况下提交。否则它必须有价值。