Django使用模型中的图标渲染CheckboxSelectMultiple(Django render CheckboxSelectMultiple with icons from the model)
我有以下型号:
class PackageCategoryChoices(models.Model): name = models.CharField(max_length=100, blank=False) icon = models.CharField(max_length=100) def __unicode__(self): return self.name和这种形式
class TripForm(forms.ModelForm): categories = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=PackageCategoryChoices.objects.all())基本上我在数据库中保存一个图标,我只是想将它渲染成一个表单。 我无法从模板访问模型信息或将额外的模型字段添加到表单字段。
我想要的东西:
<div class="checkbox"> <label for="id_categories_1"><input id="id_categories_1" name="categories" type="checkbox" value="1" /> <span class="glyphicons envelope"></span><!-- this is the icon --> Paquete pequeño<!-- this is the name --> </label> </div>我尝试更改__unicode_方法,但它与其他表单发生冲突。
I have the following model:
class PackageCategoryChoices(models.Model): name = models.CharField(max_length=100, blank=False) icon = models.CharField(max_length=100) def __unicode__(self): return self.nameand this form
class TripForm(forms.ModelForm): categories = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=PackageCategoryChoices.objects.all())Basically I'm saving an icon in the database and I just want to render it into a form. I'm unable to access the model information from the template or add extra models fields to the form field.
I want something like:
<div class="checkbox"> <label for="id_categories_1"><input id="id_categories_1" name="categories" type="checkbox" value="1" /> <span class="glyphicons envelope"></span><!-- this is the icon --> Paquete pequeño<!-- this is the name --> </label> </div>I tried changing the __unicode_ method but it made a conflict with other forms.
最满意答案
您需要ModelMultipleChoiceField并覆盖label_from_instance方法:
from django.utils.html import format_html class IconChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): return format_html('<span class="glyphicons {}"></span> {}', obj.icon, obj.name) class TripForm(forms.Form): categories = IconChoiceField(widget=forms.CheckboxSelectMultiple, queryset=PackageCategoryChoices.objects.all())You need to subclass ModelMultipleChoiceField and override label_from_instance method:
from django.utils.html import format_html class IconChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): return format_html('<span class="glyphicons {}"></span> {}', obj.icon, obj.name) class TripForm(forms.Form): categories = IconChoiceField(widget=forms.CheckboxSelectMultiple, queryset=PackageCategoryChoices.objects.all())更多推荐
发布评论