2017-01-06 13 views
1

私はCrispy Formsのドキュメントと一般的なWebでこれに対する答えを探しています。Django Crispyフォームとオプショングループ

Crispy Forms出力<optgroup>は、forms.Selectウィジェットを使用してChoiceField内にできますか?あるいは、データをコンテキストに取り込んで、テンプレート内の旧式の方法でフォームを構築する必要がありますか?

ありがとうございます!

+1

コードを表示してください。 [docs](https://docs.djangoproject.com/en/dev/ref/models/fields/#choices)のように選択肢をグループ化しましたか? – Alasdair

+0

ありがとうございます。私はCrispyのドキュメントの中で、私が基本的なDjangoのドキュメントをチェックすることを怠ったという解決策を探し求めてしまった。私は馬鹿のように感じる。 (Djangoの世界ではまだ新しいので、私を許してください) – RickZ

答えて

0
USER_GENERATED_TEMPLATES = MessageTemplate.objects.filter(Q(client=client_id) | Q(client=None) & Q(user_generated=True)) 
DEFAULT_TEMPLATES = MessageTemplate.objects.filter(Q(client=client_id) | Q(client=None) & Q(user_generated=False)) 

# Set the initial TEMPLATE CHOICES list to include the Default Templates choice object 
TEMPLATE_CHOICES = [('Default Templates',([[template.id, template.name] for template in DEFAULT_TEMPLATES]))] 

# If there are user generated templates, append the TEMPLATE_CHOICES list to include them 
if USER_GENERATED_TEMPLATES.count() > 0: 
    TEMPLATE_CHOICES.append(('Saved Templates',([[template.id, template.name] for template in USER_GENERATED_TEMPLATES]))) 

# Set the 'template' form field to a ChoiceField using the Select widget populated by the TEMPLATE_CHOICES list. 
self.fields['template'] = forms.ChoiceField(widget = forms.Select(), choices=TEMPLATE_CHOICES) 
3

choices docsには、選択肢のグループ化方法の例が示されています。

MEDIA_CHOICES = (
    ('Audio', (
      ('vinyl', 'Vinyl'), 
      ('cd', 'CD'), 
     ) 
    ), 
    ('Video', (
      ('vhs', 'VHS Tape'), 
      ('dvd', 'DVD'), 
     ) 
    ), 
    ('unknown', 'Unknown'), 
) 

あなたがこれを行う場合は、選択ウィジェットを使用すると、サクサクのフォームを使用するかどうかにかかわらず、出力optgroups必要があります。

+0

Alasdairさん、ありがとうございました。将来の参照のために以下に投稿してください。 – RickZ

関連する問題