Mampersat
Mampersat

Reputation: 382

Adding custom data to django model field

I'd like to add some info to a model field to use at form rendering time. My real model has about 15 values of varying field types (adding and removing as I dev), and it does almost everything I need, so I'd rather not create custom model fields for all of them.

I'd like to do something like this:

from django.db import models

class MyModel(models.Model):  
    cost = models.DecimalField(max_digits=5, 
        decimal_places=2, 
        custom_info= {'glyph': 'glyphicon glyphicon-usd' }
    )

And then in my form template use that glyph much like I'd use a verbose_name or help_text.

Upvotes: 2

Views: 813

Answers (1)

Scott Woodall
Scott Woodall

Reputation: 10676

Something I learned from a post just the other day. Will defining the custom information on the form instead of the model work?

When you define formfield_callback on a forms.ModelForm it will iterate over the form fields and you can manipulate them. This comes in handy when you need to add a css class to widgets and don't want to explicitly override the field. Now you only need to put formfield_callback = modify_form_field on any forms.ModelForm where you want the custom_info to show up.

from django.db import models

def add_glyphicons(model_field):
    form_field = model_field.formfield()

    if isinstance(model_field, models.IntegerField):
        form_field.custom_info = {'glyph': 'glyphicon glyphicon-usd'}
    elif isinstance(model_field, models.CharField):
        form_field.custom_info = {'glyph': 'glyphicon glyphicon-yen'}

    return form_field

class MyModel(models.Model):
    formfield_callback = add_glyphicons

    class Meta:
        model = MyModel

class MyOtherModel(models.Model):
    formfield_callback = add_glyphicons

    class Meta:
        model = MyOtherModel

Upvotes: 1

Related Questions