Django: Customizing a particular Form Field's HTML

旧街凉风 提交于 2019-12-21 04:23:12

问题


 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!


回答1:


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.



来源:https://stackoverflow.com/questions/7672189/django-customizing-a-particular-form-fields-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!