Created
October 2, 2014 13:45
-
-
Save hitsujixgit/14d794ca037f2d56f0ba to your computer and use it in GitHub Desktop.
Add class attributes to option tags of select menu on Django projects.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from django import forms | |
from myapp.models import DataGroup # Overwrite this to your model | |
from django.utils.encoding import force_text | |
from django.utils.safestring import mark_safe | |
from django.utils.html import format_html | |
class DataGroupSelect(forms.widgets.Select): | |
def render_option(self, selected_choices, option_value, option_label): | |
option_value = force_text(option_value) | |
if option_value in selected_choices: | |
selected_html = mark_safe(' selected="selected"') | |
if not self.allow_multiple_selected: | |
# Only allow for a single selection. | |
selected_choices.remove(option_value) | |
else: | |
selected_html = '' | |
# get class attrs (customize class_attr by yourself) | |
class_attr = 'xxxxxx' | |
return format_html('<option value="{0}"{1} class="{3}">{2}</option>', | |
option_value, | |
selected_html, | |
force_text(option_label), | |
class_attr) | |
class DataGroupModelChoiceField(forms.ModelChoiceField): | |
def __init__(self,*args,**kwargs): | |
kwargs['widget'] = DataGroupSelect | |
super(DataGroupModelChoiceField, self).__init__(*args,**kwargs) | |
class MyForm(forms.Form): | |
datagroup_id = DataGroupModelChoiceField(queryset=DataGroup.objects.all()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This one save my days!!!!!!! Thanks a lot!