Imoum
Imoum

Reputation: 745

Getting the selected value on a Django forms.ChoiceField

i'm working on Django and i need to know how can i get selected value in forms.ChoiceField

forms.py

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

i tried with : 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)

but Continent always return the last value in ChoiceField and what i need is the selected one.
any suggestions?

Upvotes: 3

Views: 7946

Answers (1)

okm
okm

Reputation: 23871

dict(form.fields['Continent']) looks strange, do you mean:

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

P.S. I've used continent instead of Continent as the variable name. The name w/ first uppercase is used for naming class normally.

Upvotes: 2

Related Questions