Search code examples
djangodjango-countries

How to use django countries in registration form?


I am trying to add django-countries in a registration form that will be used with django-allauth. As per instructions https://github.com/SmileyChris/django-countries I created a model

class UserProfile(models.Model):
    # Other things
    country = CountryField()

And a form

from django_countries.data import COUNTRIES

class SignupForm(forms.Form):
    # Other stuff
    country = forms.ChoiceField(choices=COUNTRIES, required=True)

    def signup(self, request, user):
        # Other Stuff
        user.userprofile.country = self.cleaned_data['country']

But when I visit the /accounts/signup/ page I get the form but for the countries select I get

<p><label for="id_country">Country:</label> <select id="id_country" name="country">
<option value="G">Q</option>
<option value="I">D</option>
<option value="K">Y</option>
 ...

Instead of country code and country name


Solution

  • You should set choices like this:

    from django_countries import countries
    COUNTRY_CHOICES = tuple(countries)
    
    class SignupForm(forms.Form):
        country = forms.ChoiceField(choices=COUNTRY_CHOICES, required=True)