Use <optgroup> with form.fields.queryset?

Is it possible to specify a request form for ForeignKey selections so that it executes a separate request and displays them in <optgroup>?

Here is what I have:

views.py

form = TemplateFormBasic(initial={'template': digest.template.id})
form.fields['template'].queryset = Template.objects.filter(Q(default=1) | Q(user=request.user)).order_by('name')

In my template model, I have default templates and user-created templates. I want them to be clearly separated in the field <select>, for example.

<select>
  <optgroup label="Default Templates">
    <option>Default 1</option>
    <option>Default 2</option>
  </optgroup>
  <optgroup label="User Templates">
    <option>User Template 1</option>
    <option>User Template 2</option>
  </optgroup>
</select>

Can this be done?

+5
source share
2 answers

I managed to figure this out using this blog below

views.py

form.fields['template'].choices = templates_as_choices(request)

def templates_as_choices(request):
    templates = []
    default = []
    user = []
    for template in Template.objects.filter(default=1).order_by('name'):
        default.append([template.id, template.name])

    for template in Template.objects.filter(user=request.user).order_by('name'):
        user.append([template.id, template.name])

    templates.append(['Default Templates', default])
    templates.append(['User Templates', user])

    return templates
+10
source

, , charfield .

CharField optgroups. :

<' > (' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' ' '4', 'Bopity')))

. , , .

+4

All Articles