Search code examples
django-modelsdjango-formsdjango-countries

How do you implement the "COUNTRIES_ONLY" setting in django_countries?


I'm new to Django and have a model that takes in user address details. I'm using a CourtryField and only want to display four country options in the form on the user profile template. I believe that I can do this using "COUNTRIES_ONLY" but am not exactly sure where this setting should go. Can someone please explain how and where I can implement the "COUNTRIES_ONLY" setting.

List of countries to display.

COUNTRIES_ONLY = [
        "GB",
        "GG",
        "IM",
        "JE",
    ]

Model

from django_countries.fields import CountryField


class UserProfile(models.Model):
    # A user profile model for maintaining default
    # delivery information & order history

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    default_full_name = models.CharField(max_length=50, null=True, blank=True)
    default_email = models.EmailField(max_length=254, null=True, blank=True)
    default_phone_number = models.CharField(max_length=11, null=True, blank=True)
    default_street_address1 = models.CharField(max_length=80, null=True, blank=True)
    default_street_address2 = models.CharField(max_length=80, null=True, blank=True)
    default_town_or_city = models.CharField(max_length=40, null=True, blank=True)
    default_county = models.CharField(max_length=80, null=True, blank=True)
    default_postcode = models.CharField(max_length=8, null=True, blank=True)
    default_country = CountryField(null=True, blank=True, default='GB')

    def __str__(self):
        return self.user.username

Solution

  • You define these in the settings.py file:

    # settings.py
    
    # …
    
    COUNTRIES_ONLY = [
        "GB",
        "GG",
        "IM",
        "JE",
    ]

    you thus can define different settings modules and load the appropriate one with the --settings flag of manage.py.

    The django-countries package will load the setting through django.conf.settings, so if you run manage.py with a different settings module, it will use the values from that module.