django forms - 基于get request url参数选择的选项

时间:2016-06-20 16:16:27

标签: django django-forms

我有一个看起来像这样的表单 - 一个有下拉选择的表单:

class ContactUs(forms.Form):

TYPES = (
    ('hi', 'Say Hi'),
    ('restaurant', 'Introducing a Restaurant'),
    ('event', 'An Event is coming up'),
    ('promotion', 'Interesting Promotion'),
)
subject = forms.ChoiceField(choices=TYPES)

我想从request.GET.get('subject')读取,以便我可以动态选择

所以它看起来像这样:

subject = forms.ChoiceField(choices=TYPES, initial=request.GET.get('subject'))

显然,选择是:嗨,餐厅,活动或促销,网址看起来像这样:

http://localhost:8000/contact?subject=promotion

问题是我不能做request.GET.get('subject')

我们如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

contact_us = ContactUs(initial={'subject': request.GET.get('subject')})

Django form initial