Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 765
Aldarund Avatar asked Mar 31 '11 11:03

Aldarund


People also ask

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

Which method has a form instance which runs validation routines for all its fields?

The run_validators() method on a Field runs all of the field's validators and aggregates all the errors into a single ValidationError .

How do you create a model form?

First, create a model that contains fields name and other metadata. It can be used to create a table in database and dynamic HTML form. This file contains a class that inherits ModelForm and mention the model name for which HTML form is created. Write a view function to load the ModelForm from forms.py.


1 Answers

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.

like image 160
dting Avatar answered Oct 10 '22 16:10

dting