Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Customizing a particular Form Field's HTML

 class ItemForm(forms.ModelForm):
     description = forms.CharField(label='Description', max_length=250, widget=forms.Textarea, required=False)
     image = forms.ImageField(label='Item Picture', max_length=50, required=False)
     start = forms.DateField(widget=SelectDateWidget, required=False)
     end = forms.DateField(widget=SelectDateWidget, required=False)
     cost_price = forms.CharField(label='Cost Price Per Unit', widget=???, max_length=5)

     class Meta:
         model = Item
         fields = ('image',
                   'name',
                   'description',
                   'quantity',
                   'start',
                   'end',
                   'cost_price',
                   'selling_price',
                   )

I need to include a text variable in front of the cost_price field.

From the docs, I know that the widget class is what I need to modify but I'm not too sure on how to go about doing it.

UPDATE

So each field in my form is represented by {{ field }} in my template. This {{ field }} generates the HTML for that particular field. I would like to modify the HTML of the cost_price field such that I can append a variable {{ currency_type }} to the front of the HTML. So it should look something like this:

<span>USD</span><input type="text" name="cost_price" id="id_cost_price">

Right now I am including this {{ currency_type }} variable through template logic. I was wondering if I could do this through customizing the form field's HTML hence the question. Hope this explains it better!

like image 621
super9 Avatar asked Oct 06 '11 09:10

super9


1 Answers

You can create custom form widget that inherits from the TextInput widget (which is used for CharField) and overrides it's render method. That way you can do exactly what you want to - insert custom HTML before regular TextInput widget HTML.

from django.utils.safestring import mark_safe
from django.forms import widgets

# ...

# your custom widget class
class CostPriceWidget(widgets.TextInput):
    def render(self, name, value, attrs=None):
        return mark_safe(u'''<span>USD</span>%s''' % (super(CostPriceWidget, self).render(name, value, attrs)))

# your form class
class ItemForm(forms.ModelForm):
    # ...
    cost_price = forms.CharField(label='Cost Price Per Unit', widget=CostPriceWidget, max_length=5)
    # ...

Hope this helps.

like image 121
MisterMetaphor Avatar answered Oct 16 '22 06:10

MisterMetaphor