2

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.

1
  • Won't it be easier to customize the form and not the model? Commented Mar 1, 2014 at 19:53

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.