Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8501919
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T01:20:39+00:00 2026-06-11T01:20:39+00:00

class CreateCourseForm(ModelForm): category = forms.ModelChoiceField( queryset=Category.objects.all(), empty_label=, #widget=CustomCourseWidget() ) class Meta: model = Course

  • 0
class CreateCourseForm(ModelForm):
        category = forms.ModelChoiceField(
            queryset=Category.objects.all(),
            empty_label="",
            #widget=CustomCourseWidget()
        )

    class Meta:
        model = Course
        fields = ('title', 'description', 'category')

    def __init__(self, *args, **kwargs):
        super(CreateCourseForm, self).__init__(*args, **kwargs)
        self.fields['category'].widget.attrs['class'] = 'chzn-select'
        self.fields['category'].widget.attrs['data-placeholder'] = u'Please select one'

With the code above, I’m getting a select-box with all the Category-Objects listed. What I’m trying to do is to add a

<optgroup>VALUE</optgroup> 

HTML-element to specific Category-Objects (the ones with Category.parent == null).

Does anyone know how to do that? Thanks a lot!

PS: I already tried converting the QuerySet to a Choices-Set (e.g. http://dealingit.wordpress.com/2009/10/26/django-tip-showing-optgroup-in-a-modelform/), which works fine for rendering the HTML – until I try to save the results into the DB, where a mismatching occurs (ValueError).

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T01:20:41+00:00Added an answer on June 11, 2026 at 1:20 am

    Here is my current solution. It might be a dirty fix, but it works fine 🙂

    class CustomCourseWidget(forms.Select):
        #http://djangosnippets.org/snippets/200/
        def render(self, name, value, attrs=None, choices=()):
            from django.utils.html import escape
            from django.utils.encoding import smart_unicode
            from django.forms.util import flatatt
    
            if value is None:
                value = ''
            final_attrs = self.build_attrs(attrs, name=name)
            output = [u'<select%s>' % flatatt(final_attrs)]
            output.append(u'<option value=""></option>') # Empty line for default text
            str_value = smart_unicode(value)
            optgroup_open = False
            for group in self.choices:
                option_value = smart_unicode(group[0])
                option_label = smart_unicode(group[1])
                if not ">" in option_label and optgroup_open == True:
                    output.append(u'</optgroup>')
                    optgroup_open = False
                if not ">" in option_label and optgroup_open == False:
                    output.append(u'<optgroup label="%s">' % escape(option_label))
                    optgroup_open = True
                if " > " in option_label:
                    #optgroup_open = True
                    selected_html = (option_value == str_value) and u' selected="selected"' or ''
                    output.append(u'<option value="%s"%s>%s</option>' % (escape(option_value), selected_html, escape(option_label.split(" > ")[1])))
    
            output.append(u'</select>')
            return mark_safe(u'\n'.join(output))
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

class Widget; std::vector< std::shared_ptr<Widget> > container class Criterium { public: bool operator()(const Widget& left,
class Book(models.Model): name = models.CharField(max_length=127, blank=False) class Author(models.Model): name = models.CharField(max_length=127, blank=False) books =
class Tag(models.Model): name = models.CharField(maxlength=100) class Blog(models.Model): name = models.CharField(maxlength=100) tags = models.ManyToManyField(Tag) Simple
class Foo(models.Model): title = models.CharField(max_length=20) slug = models.SlugField() Is there a built-in way to
class Api::StoresController < ApplicationController respond_to :json def index @stores = Store.all(:include => :products) respond_with
class myClass (models.Model): related_operation = models.ForeignKey('self', null = True) __related_operation = None def save(self,
Class 1 private void checkDuplicateCustomer(BulkCustomerVO bulkCustomerVO) { PagedDuplicateCustomerVO duplicateCustomerVO = new PagedDuplicateCustomerVO(); duplicateCustomerVO.setCustomer(bulkCustomerVO.getCustomerVO()); duplicateCustomerVO
class StartAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): print "Hello" start.add_argument('-s', '--start', action=StartAction) I
class A: pass def b(self): print('b') A.b = b a = A() At this
class X { int i; public: X() { i = 0; } void set(int

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.