Django ModelFieldChoice 选择传递值

您好,我正在使用 ModelFieldChoice 在模型“文章”中设置来自提供者的外键(文章属于提供者)。模板中的选择与数据库中的所有提供程序一起正确显示,但是当我尝试发布表单时,它会抛出一个错误,表明即使我传递了选择值,它也是必需的。此外,我在数据库中为文章设置了值,当我尝试编辑它时,表单中的所有字段都填充了除选择之外的正确数据。这些是我的模型,我将不胜感激的帮助,谢谢!抱歉,如果我做错了什么,这是我第一次在 stackoverflow 上发帖。Article.py 模型


class Article(models.Model):

     codigo = models.CharField(max_length=100, verbose_name='Codigo')

     proveedor = models.ForeignKey(Provider, on_delete=models.CASCADE)

     descripcion = models.CharField(max_length=200, verbose_name='Descripcion',null=False, blank=True)

     marca = models.CharField(max_length=100, verbose_name='Marca',null=True, blank=True)

     rubro = models.CharField(max_length=100, verbose_name='Rubro',null=True, blank=True)

     nota = models.TextField(verbose_name='Nota',null=True)

     costo = models.CharField(max_length=50, verbose_name='Costo',null=False, blank=True)

     created = models.DateTimeField(auto_now_add=True, verbose_name="Fecha de creación",null=True, blank=True)

     updated = models.DateTimeField(auto_now=True, verbose_name="Fecha de edición",null=True, blank=True)


class Meta:

    verbose_name = "articulo"

    verbose_name_plural = "articulos"

    ordering = ['-descripcion']


def __str__(self):

    return self.descripcion

在views.py中,当我打印“proveedor_id”时,该值正确显示在控制台中,但“is_valid()”失败并打印错误"<ul class="errorlist"><li>proveedor<ul class="errorlist"><li>Este campo es obligatorio.</li></ul></li></ul>"(必填字段,就好像我没有传递它一样)


ibeautiful
浏览 87回答 1
1回答

largeQ

首先,将ArticleCreate序列化器简化为这样:class ArticleCreate(forms.ModelForm):&nbsp; class Meta:&nbsp; &nbsp; model = Article然后在请求传递proveedor字段中,不是proveedor_id. 在 Django/DRF 中,您应该使用"{{association_name}}": id模式传递关联 ID,而不是"{{association_name}}_id": id所以你也可以简化你的观点:def add_article(request):if request.method == 'POST':&nbsp; create = ArticleCreate(request.POST)&nbsp; if create.is_valid():&nbsp; &nbsp; create.save()&nbsp; ...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python