![](/img/trans.png)
[英]How to use a CreateView and include fields in form for new ForeignKey model?
[英]How to use parents model fields in the model form?
我使用django 1.9,并具有一些模型继承,例如:
class TimeStampedModel(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
之后,我使用该模型将created
和modified
模型添加到我的模型中。 但是我不能在表单中使用此字段。 例如:
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 ...
如何将该字段添加到表单? 我在数据库架构中有它,但Django形式没有得到它。
当您调用Model.save()
时, auto_now=True
字段将自动更新。 有关更多详细信息, 请参见https://docs.djangoproject.com/zh-CN/1.11/ref/models/fields/#datefield auto_now =无法从ModelForm访问真正的字段,按照目前的实现,将auto_now或auto_now_add设置为True会导致字段具有editable = False和blank = True设置。
由于您使用的是1.9,因此发生的问题已从1.10更改为
这样您就可以更新Django版本,以便可以使用它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.