【问题标题】:could not be changed because the data didn't validate. (Django)无法更改,因为数据未验证。 (姜戈)
【发布时间】:2013-09-18 04:16:37
【问题描述】:

模型.py

class Produto(models.Model):
      uuid = models.CharField(max_length=50, primary_key=True, editable=False, default=gen_uuid)
      produto = models.CharField(max_length=100, unique=False, verbose_name="Item")

      class Meta:
            verbose_name = "Produto"
            verbose_name_plural = "Produtos"

class Item(models.Model):
      uuid = models.CharField(max_length=50, primary_key=True, editable=False, default=gen_uuid)
      tipo = models.CharField(max_length=100, null=False, blank=True, unique=False, verbose_name="tipo_mtr")

      class Meta:
            verbose_name = "Item"
            verbose_name_plural = "Itens"

class Orcamento(models.Model):
      uuid              = models.CharField(max_length=50, primary_key=True, editable=False, default=gen_uuid)
      quantidade        = models.IntegerField(max_length=10, unique=False, null=True, verbose_name="qtde")
      produto           = models.ForeignKey(Produto, verbose_name="Produto")
      tipo              = models.ManyToManyField(Item, verbose_name="Item")

      class Meta:
              verbose_name = "Orcamento"
              verbose_name_plural = "Orcamentos"
              unique_together     = ("produto", "uuid")

      def __unicode__(self):
         return unicode(self.produto)

我的 forms.py (OrcamentoForm)

class OrcamentoForm(ModelForm):
      tipo_id               = ModelMultipleChoiceField(queryset=Item.objects.all(), required=True, widget=SelectMultiple(attrs={"style":"width:500px",}), help_text="Coloque o Tipo de Medida - Requerido")
      quantidade            = IntegerField(label="Quantidade", required=True, help_text="Coloque a Quantidade - Requerido")
      produto_id            = ModelMultipleChoiceField(queryset=Produto.objects.all(), widget=SelectMultiple(attrs={"style":"width:500px",}), required=True, help_text="Escolha o Produto - Requerido")

      def __init__(self, *args, **kwargs):
        super(OrcamentoForm, self).__init__(*args, **kwargs)
        # without the next line label_from_instance does NOT work 
        self.fields['produto_id'].queryset = Produto.objects.all()
        self.fields['produto_id'].label_from_instance = lambda Produto: "%s" % (Produto.produto)

        self.fields['tipo_id'].queryset = Item.objects.all()
        self.fields['tipo_id'].label_from_instance = lambda Item: "%s" % (Item.tipo)

      class Meta:
          model = Orcamento
          fields = ["quantidade", "tipo_id", "produto_id" ]

我的意见.py

def orcamento(request):
        form = OrcamentoForm(request.POST or None, request.FILES or None)
        if request.method == 'POST':
               form.save()
               return render_to_response("webSite/teste.html", context_instance = RequestContext(request))
        else:
            return render_to_response("webSite/orcamento.html", {"form": form }, context_instance=RequestContext(request))

views.py 中使用if form.is_valid():,不要将表单保存在表mysql 中。

帮帮我:(

【问题讨论】:

  • 尝试form.save() 而不是form.save
  • stackoverflow 中的第一个问题,我有点迷茫:(
  • 首先 - 修复您的问题的降价。如您所见,一些代码行被删除了
  • 您需要将代码缩进 4 个空格才能正确显示(编辑器正在使用降价)
  • 那么,你有什么?保存表单时,数据不会出现在数据库中?你有没有提出任何错误?

标签: django validation django-forms


【解决方案1】:

如果在执行form.is_valid() 检查时没有保存表单,则表示该表单无效。在这种情况下,我们应该为每个字段显示表单发现的错误。为此,首先您应该将表单数据传递给模板,如果表单无效。

#views.py
def orcamento(request):
    form = OrcamentoForm(request.POST or None, request.FILES or None)
    if request.method == 'POST':
        if form.is_valid():
            form.save()
            return render_to_response("webSite/teste.html", context_instance = RequestContext(request))
    #Following will run in all cases except when form was valid
    return render_to_response("webSite/orcamento.html", {"form": form }, context_instance=RequestContext(request))

您可以在模板中显示表单引发的所有错误或字段错误。详细了解见django documentation

【讨论】:

  • 是的......我确实出现在表单错误中......模板tipo_id中的错误这个字段是必需的。 produto_id 此字段为必填项。
  • 是 ModelMultipleChoiceField 的外键问题 ... :9 ... 但不是发现解决方案:(
【解决方案2】:

我打错了同样的错误 .is_valid().is_valied()。 您可能想检查是否是这种情况。

【讨论】:

    【解决方案3】:

    如果您从未将() 包含在.is_valid() 中,也会发生此错误。将有效性检查器设置为 .is_valid: 也会引发相同的错误。

    【讨论】:

      【解决方案4】:

      这个错误发生在我身上,但我通过在 is_valid 中添加括号解决了它,它变成了 is_valid() 并且错误消失了,再也没有回来

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-09
        • 1970-01-01
        • 2023-04-08
        • 1970-01-01
        • 2020-08-17
        • 2012-12-06
        • 2017-02-08
        • 1970-01-01
        相关资源
        最近更新 更多