我有一个抽象模型,它定义了一些字段,以及从它继承的其他模型。如果我为这个模型定义了一个表单,基本字段没有定义,我不能在表单中使用它。
如果我用字段指定它,我会收到此错误:
异常值:为经销商指定的未知字段(created_at、updated_at)
异常位置:C:\Python27\lib\site-packages\django\forms\models.py in 新品 , 第 215 行
这是我的代码:
class BaseModel(models.Model):
created_at = models.DateTimeField(default=datetime.now, editable=False)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Reseller(BaseModel):
name = models.CharField(_("name"), max_length=255, unique=True)
class ResellerForm(forms.ModelForm):
class Meta:
model = Reseller
fields = ('name','created_at','updated_at')
UPD
使用这三个类的新空项目可以清楚地重现它。表单导入失败
从 jjj.forms 导入 ResellerForm
回溯(最近一次调用最后一次):
文件“”,第 1 行,在
文件“C:\Users\ShapeR\PycharmProjects\djt\jjj\forms.py”,第 4 行,在
类 ResellerForm(forms.ModelForm):
文件“C:\Python27\lib\site-packages\django\forms\models.py”,第 214 行,在 __new__ 中
引发字段错误(消息)
FieldError:为经销商指定的未知字段(created_at、updated_at)
最佳答案
created_at = models.DateTimeField(default=datetime.now, editable=False)
updated_at = models.DateTimeField(auto_now=True)
http://docs.djangoproject.com/en/dev/ref/models/fields/#editable
Field.editable
If False, the field will not be editable in the admin or via forms automatically generated from the model class. Default is True.
还
Note
As currently implemented, setting auto_now or auto_now_add to True will cause the field to have editable=False and blank=True set.
关于django - 具有继承模型的 ModelForm 的表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5499315/