如何在模型窗体中使用父模型字段?

2023-09-22 19:12:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用django 1.9并继承了一些模型,例如:

class TimeStampedModel(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

之后,我使用这个模型将createdmodified添加到我的模型中。但是我不能在表单中使用这个字段。例如:

class Customer(TimeStampedModel):
    first_name = models.CharField(max_length=250, blank=True,
                                  null=True, default=None)
    last_name = models.CharField(max_length=250, blank=True,
                                 null=True, default=None)

以及表格代码:

class CustomerForm(forms.ModelForm):
    class Meta:
         model = Customer
         fields = ('first_name', 'last_name', 'modified')
         readonly_fields = ('modified', )

我得到一个错误:

django.core.exceptions.FieldError: Unknown field(s) (modified) specified for ...

如何将此字段添加到窗体中?我在DB模式中有它,但是django表单没有得到它。你知道吗


Tags: djangoname模型true表单automodelscustomer
2条回答

auto_now=True字段在调用Model.save()时自动更新。 更多详情https://docs.djangoproject.com/en/1.11/ref/models/fields/#datefield auto\u now=True不能从ModelForm访问字段, 按照当前的实现,将auto\u now或auto\u now\u add设置为True将导致字段设置editable=False和blank=True。你知道吗

出现的问题是因为您使用的是1.9,而此问题已从1.10更改为

所以你可以更新你的django版本,这样你就可以使用这个

相关问题 更多 >