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 settings.py, add this −

INSTALLED_APPS += [ 'django_countries']

Example

In app's urls.py

from django.urls import path
from . import views

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

First setup your urls.

In views.py

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

   else:
      form=SalaryForm()
   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>
<html>
   <head>
      <title>
         TUT
      </title>
      <style>

      </style>
   </head>
   <body>
      <h2>FORM</h2>
      <form action="/" method="post">
         {% csrf_token %}
         {{ form }}
         <input type="submit" value="Submit">
      </form>
   </body>
</html>

This is the front-end html of our form.

In models.py

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

# Create your models here.
class Data(models.Model):
   Name=models.CharField(max_length=100)
   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.

Output


Updated on: 26-Aug-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements