Вопрос

I am having an issue trying to get a simple choice field to return its options to a html page in my application. I have been looking at several other questions 1, 2 and some online tutorials but cant seem to get it right.

My current code does not return the dropdown, it only returns the submit button.

Optimally I would like to return the countries in a Dropdown list with the option of making it a required field.

I am able to return similar views using models.Model using this approach but cant seem to get the ChoiceField from forms.Form working.

Any help is much appreciated, Thanks.

models.py

from django import forms

class CountryChoiceTwo(forms.Form):

    IRELAND = 'IR'
    ENGLAND = 'EN'
    FRANCE = 'FR'
    SCOTLAND = 'SC'
    WALES = 'WA'
    ITALY = 'IT'

    COUNTRY = (
        (IRELAND, "Ireland"),
        (ENGLAND, "England"),
        (FRANCE, "France"),
        (SCOTLAND, "Scotland"),
        (WALES, "Wales"),
        (ITALY, "Italy"),
               )

    origin = forms.ChoiceField(widget=forms.Select(), choices=COUNTRY, initial= IRELAND)

    def __unicode__(self):
        return self.origin

views.py

from books.models import CountryChoiceTwo

def ContactForm(request):

    form = CountryChoiceTwo(initial={'origin':COUNTRY[1]})   
    return render(request, 'country_choice.html', {'form': form} )

country_choices.html

<h2>What country are you from?</h2>


<form action="" method="post">
    {% csrf_token %}

    {{form.as_p}}


<input type="submit" value="Vote" />               
</form>
Это было полезно?

Решение

COUNTRY is not defined in the scope of your view function.

You can reference COUNTRY from your form by prefixing it with the class name:

def ContactForm(request):
    form = CountryChoiceTwo(initial={'origin': CountryChoiceTwo.COUNTRY[1]})
    return render(request, 'country_choice.html', {'form': form} )
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top