在Django forms.ChoiceField上获取所选值

时间:2013-03-28 14:00:29

标签: django django-forms

我正在研究Django,我需要知道如何在forms.ChoiceField

中获得选定值

forms.py

class FilterForm(forms.Form):
    continent = forms.ChoiceField(choices=Select_continent()) 

我尝试过: views.py

def Select_continent():
    db = MySQLdb.connect("localhost", "root", "aqw", "PFE_Project")
    cursor = db.cursor()
    sql = "SELECT Continent FROM myform_servercomponents"

    try:
        cursor.execute(sql)
        results = cursor.fetchall()
        continents = []
        i=0
        for row in results:
            continents.append(('i',row[0]))
            i+=1
    except:
        print "Error: unable to fetch data"
    db.close()
    return continents
def affiche_all(request, currency):
    if request.method == 'POST':                                                                                                                                                 
        form = FilterForm(request.POST)                                                                                                                                            
        if form.is_valid() : 
            Continent = form.cleaned_data['Continent']
            Continent = dict(form.fields['Continent'])[Continent]
            url = reverse('affiche_all', args=(),   kwargs={'continent': Continent})
            return HttpResponseRedirect(url)

Continent始终返回ChoiceField中的最后一个值,我需要的是所选的值。
有什么建议吗?

1 个答案:

答案 0 :(得分:1)

dict(form.fields['Continent'])看起来很奇怪,你的意思是:

continent = dict(continents())[form.cleaned_data['Continent']]
# or
continent = dict(form.fields['Continent'].choices)[form.cleaned_data['Continent']]

P.S。我使用continent代替Continent作为变量名称。 w / first大写的名称通常用于命名类。