SmileyChris / django-countries

A Django application that provides country choices for use with forms, flag icons static files, and a country field for models.

Home Page:https://pypi.python.org/pypi/django-countries

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Cannot set Default country

sharad740 opened this issue · comments

In forms.py
from django_countries.widgets import CountrySelectWidget
from django import forms 
from enroll.models import Person

class PersonForm(forms.ModelForm):
    class Meta:
        model = Person
        fields = ('name', 'country')
        widgets = {'country': CountrySelectWidget()}

Returns : Select Country by default

In models.py

from django.db import models
from django_countries.fields import CountryField

class Person(models.Model):
    name = models.CharField(max_length=100,)
    country = CountryField(blank_label='(select country)',blank=True)
    
    def __str__(self):
        return self.name

Setting a default on the CountryField removes the blank choice.

See favourite_country example here:

class Person(models.Model):
name = models.CharField(max_length=50)
country = CountryField()
other_country = CountryField(
blank=True, countries_flag_url="//flags.example.com/{code}.gif"
)
str_attr_country = CountryField(blank=True, countries_str_attr="name")
favourite_country = CountryField(default="NZ")

Tested here:
def test_no_blank_choice(self):
form = forms.PersonForm()
self.assertEqual(
form.fields["favourite_country"].choices[0], ("AF", "Afghanistan")
)