django - 具有继承模型的 ModelForm 的表单字段

标签 django django-models django-forms

我有一个抽象模型,它定义了一些字段,以及从它继承的其他模型。如果我为这个模型定义了一个表单,基本字段没有定义,我不能在表单中使用它。

如果我用字段指定它,我会收到此错误:

异常值:为经销商指定的未知字段(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/

相关文章:

python - Django 表格内联翻译(解析器)缺少 2 个必需的位置参数 : model and admin_site

python - Django - 什么是最佳实践 - 计算字段值

django - 如何在 Django ORM 中查询不区分大小写的数据?

python - 值错误 : invalid literal for int() with base 10 with django. 设置()

django - 我们如何为 Django 表单中的浮点字段提供占位符?

python - Django:数据库级别或代码级别的TextField(字符串)数据压缩

python - WSGI 作为 AuthFormProvider

django - 使用 _set.all 时颠倒顺序

python - 在 Django 1.10 中制作表单并收到 CSRF 验证失败。请求已中止

Django:在一段时间后更新模型属性