Aldarund
Aldarund

Reputation: 17621

Form fields for ModelForm with inherited models

I have a abstract model that defines some fields, and other models that inherited from it. And if i define a form for this model, base fields not defined and i cannot use it in form.

If i specify it with fields i get this error:

Exception Value: Unknown field(s) (created_at, updated_at) specified for Reseller

Exception Location: C:\Python27\lib\site-packages\django\forms\models.py in new, line 215

Here my code:

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

Its clearly reproduceble with new empty project with this three classes. Its failing on form import

 from jjj.forms import ResellerForm
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Users\ShapeR\PycharmProjects\djt\jjj\forms.py", line 4, in 
    class ResellerForm(forms.ModelForm):
  File "C:\Python27\lib\site-packages\django\forms\models.py", line 214, in __new__
    raise FieldError(message)
FieldError: Unknown field(s) (created_at, updated_at) specified for Reseller

Upvotes: 14

Views: 6206

Answers (2)

dting
dting

Reputation: 39287

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.

also

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.

Upvotes: 14

Greg Haskins
Greg Haskins

Reputation: 6794

If your indentation matches the excerpt above, then you may need to properly nest that Meta subclass inside BaseModel. Otherwise, django will try doing multi-table inheritance--but that should still work with what you're trying to do (unless you have a non-standard setup, e.g. django-nonrel).

What code is triggering this exception, just importing the module?

Upvotes: 0

Related Questions