1

I have the following models:

class RegionCategory(models.Model):
    """Categories of regions"""

    symbol = models.CharField(max_length=15)
    description = models.CharField(max_length=50)

class Region(models.Model):
    """Region model"""

    region = models.CharField(max_length=30)
    category = models.ForeignKey(RegionCategory)

class md_orderlog(models.Model):
    """Order log model"""

    order_region = models.ForeignKey(Region)

Nothing uncommon, just a model with a foreign key to another model.

I have a ModelForm also:

class md_orderlogForm(forms.ModelForm):
    """Model form of md_orderlog model"""

    def __init__(self, *args, **kwargs):
        super(md_orderlogForm, self).__init__(*args, **kwargs)

        self.fields['order_region'] = forms.ModelChoiceField(
              label=("Project Region"), widget=forms.Select,   
              queryset=Region.objects.all())

What I want and I don't know how to do is to customize the order_region field in the form so the select show the Region items divided by the category, something like this:

Category1
    Region1
    Region2
    Region3 
Category2
    Region4
    Region5
    Region6

Any ideas?, thanks!

Pedro Muñoz
  • 285
  • 3
  • 16
  • 1
    Maybe this will help: [How to group the choices in a Django Select widget?](http://stackoverflow.com/questions/5080828/how-to-group-the-choices-in-a-django-select-widget) – César Oct 30 '15 at 22:15
  • Even better: [DJANGO: ModelChoiceField optgroup tag](http://stackoverflow.com/questions/15210511/django-modelchoicefield-optgroup-tag) – César Oct 30 '15 at 22:21
  • 2
    Thos worked very well! https://dealingit.wordpress.com/2009/10/26/django-tip-showing-optgroup-in-a-modelform/ – Pedro Muñoz Oct 30 '15 at 22:59
  • @PedroMuñoz cool, didnot know about it – doniyor Oct 30 '15 at 23:05

0 Answers0