[Django]-How can I set arbitrary attributes on Django Model Fields, then access them in a ModelForm?

1👍

Note that publishable should be a property on the forms.Field, not on the models.Field, so that it will appear in the template.

You can add this explicitly on the fields you wish to have publishable in the form’s initiation, and it will be available to you while rendering:

class PublishableForm(forms.Form):
    name = forms.CharField()

    def __init__(*args, **kwargs)
       super(PublishableForm, self).__init__(*args, **kwargs)
       self.name.publishable = True

0👍

You can also make kind of decorator for model fields:

def publishable(field):
    field.publishable = True
    return field

#...

name = publishable(models.CharField(...))

Then override form’s __init__ to use these fields.

Also don’t forget that using {{ form.name }} in template returns BoundField. To get original form field you should use {{ form.name.field }}.

Leave a comment