views:

61

answers:

3

Hi!

I'm trying to do a form, with gender choices. The user could choice between male or female.

What I have now in forms.py:

class GenderForm(forms.Form):
    demo = DemoData.objects.all()
    GENDER_CHOICES = [
        ('Male', 'Masculino'),
        ('Female', 'Feminino')]

    gender = forms.ModelChoiceField(demo, widget=Select(), required=True)
    choices_distlabel = [('', '')] + GENDER_CHOICES
    gender.choices =  choices_distlabel

in the template:

<form action="" method="post">
    {% for field in form_gender %}
        {{ field }}
    {% endfor %}

<input type="submit" value="Submit" />
 </form> 
{% if idgender %}
    <img src="/age_gender/{{ idgender }}.png" alt="Graph"/>
{% endif %} 

the views:

 if form_gender.is_valid():
        gender = form_gender.cleaned_data['gender']
        gender = gender.gender
        if gender:
            idgender = gender
        return render_to_response('age.html', {'form_gender': form_gender, 'idgender': idgender }) 

the form is done and works, but the problem is when I click on the submit button nothing happen. He is not given me the information

A: 

I don't understand why you've defined DemoDataForm in both models.py and forms.py, once as a ModelForm and once as a plain form. Because of that, it's impossible to tell from the code you've posted exactly which class you're instantiating.

I would say, drop the version in forms.py, move the one in models.py into forms.py, and use that. But first you'll need to fix a slight bug - instead of:

fields = ('gender')

you need

fields = ('gender',)

because a one-item tuple always needs a comma, otherwise Python will try to iterate through the string.

Daniel Roseman
Actually it was a silly mistake, I forgot a brackets. sorry about that, but I wasn't see the error. But thank you for your suggestion. I saw in django documentation and I tried like that
Pat
@Daniel I gone update my question and post my final result. Feel free to suggest improvements :)
Pat
A: 

In Above code, submit button is outside form tags ? Shouldn't it be inside the form tags?

Srikanth Chundi
My mistake writing. It' s not that the problem since I only made that mistake copying here
Pat
+1  A: 

You have to define url where post data will be sent

This will send post data to url /my_app/my_view/

<form action="/my_app/my_view/" method="post">
    {% for field in form_gender %}
        {{ field }}
    {% endfor %}

<input type="submit" value="Submit" />
</form> 

This will send post data to current url you are on.

<form action="." method="post">
    {% for field in form_gender %}
        {{ field }}
    {% endfor %}

<input type="submit" value="Submit" />
</form> 
Dominik Szopa
I tried that way also, but that's not the reason why it doesn't work. Nothing change..
Pat