How to make a Country field in Django?

If you need to add a location field in your form or database, you can do that using charfield but it is still not that good idea. In Django, we have a third-party package called 'django-countries' that provides the country field. In this article, let's see how to use django-countries to add a Country field in Django.

First, create a Django project and an app.

Add the app in INSTALLED_APPS and set up urls.

Install the django-countries module −

pip install django-countries

In, add this −

INSTALLED_APPS += [ 'django_countries']


In app's

from django.urls import path
from . import views

urlpatterns = [
   path('', views.home, name="home"),

First setup your urls.


from django.shortcuts import render
from django import forms
from .models import Data
class SalaryForm(forms.ModelForm):
   class Meta:
def home(request):
   if request.method=='POST':
      if form.is_valid():

   return render(request,'home.html',{'form':form})

Here we simply created a form and rendered it in GET request handler of our view. In POST handler, we save the form data.

Create a templates folder in app directory and a home.html in it. In home.html

<!DOCTYPE html>

      <form action="/" method="post">
         {% csrf_token %}
         {{ form }}
         <input type="submit" value="Submit">

This is the front-end html of our form.


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

# Create your models here.
class Data(models.Model):
   salary = models.CharField(max_length=20)
   country_of_work = CountryField(blank=True)

Here we created a model in which we simply added a country field which will store the country data.

Now, make migrations and migrate. You are all done. Now, you can proceed to check the output.


Updated on: 26-Aug-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started