I'm adding a new library : Django_countries
on my Django Project and I get a little problem with my form.
I get correctly my countries list inside my form, but I don't display flags with widgets beside each country.
I'm using this documentation : https://pypi.python.org/pypi/django-countries But I don't find a way to display country flags even if all elements seem to work.
This is my models.py file from BirthCertificate application :
#-*- coding: utf-8 -*-
from django.db import models
from Identity.models import Country, Identity
from django.utils.encoding import force_text
from django_countries.fields import CountryField
######################################
# Choix à l'utilisateur pour le sexe #
######################################
SEX_CHOICES = (
('Masculin', 'Masculin'),
('Feminin', 'Feminin')
)
####################################################################################
# Création d'une table permettant de renseigner toutes les informations concernant #
# l'enfant et reprise des champs pour les parents #
####################################################################################
class BirthCertificate(models.Model):
lastname = models.CharField(max_length=30, null=False, verbose_name='Nom de famille')
firstname = models.CharField(max_length=30, null=False, verbose_name='Prénom(s)')
sex = models.CharField(max_length=8, choices=SEX_CHOICES, verbose_name='Sexe')
birthday = models.DateField(null=False, verbose_name='Date de naissance')
birthhour = models.TimeField(null=True, verbose_name='Heure de naissance')
birthcity = models.CharField(max_length=30, null=False, verbose_name='Ville de naissance')
birthcountry = CountryField(blank_label='(Pays de naissance)')
fk_parent1 = models.ForeignKey(Identity, related_name='ID_Parent1', verbose_name='ID parent1', null=False)
fk_parent2 = models.ForeignKey(Identity, related_name='ID_Parent2', verbose_name='ID parent2', null=False)
This is my forms.py file :
#-*- coding: utf-8 -*-
from django import forms
from BirthCertificate.models import *
from django_countries.widgets import CountrySelectWidget
class CustomLabelModelChoiceField(forms.ModelChoiceField):
def __init__(self, *args, **kwargs):
self._label_from_instance = kwargs.pop('label_func', force_text)
super(CustomLabelModelChoiceField, self).__init__(*args, **kwargs)
def label_from_instance(self, obj):
return self._label_from_instance(obj)
class BirthCertificateForm(forms.ModelForm):
fk_parent1 = CustomLabelModelChoiceField(Identity.objects.filter(sex = "Masculin"), required=False, label = "Père", label_func=lambda obj: '%s %s %s %s' % (obj.lastname, obj.firstname, obj.birthday, obj.birthcity))
fk_parent2 = CustomLabelModelChoiceField(Identity.objects.filter(sex = "Feminin"), required=False, label = "Mère", label_func=lambda obj: '%s %s %s %s' % (obj.lastname, obj.firstname, obj.birthday, obj.birthcity))
class Meta :
model = BirthCertificate
fields = '__all__'
widgets = {'country': CountrySelectWidget()}
def __init__(self, *args, **kwargs):
super(BirthCertificateForm, self).__init__(*args, **kwargs)
for key, value in self.fields.iteritems() :
self.fields[key].widget.attrs.update({'class':'form-fields'})
class IdentityForm(forms.ModelForm) :
class Meta :
model = Identity
fields = '__all__'
widgets = {'country': CountrySelectWidget()}
My form looks like :
EDIT :
My HTML template corresponding to BirthCertificate Form :
{% extends 'Base_BirthCertificate.html' %}
{% load staticfiles %}
{% block content %}
<!-- ############### -->
<!-- Page principale -->
<!-- ############### -->
<h1 align="center"> Formulaire d'acte de naissance </h1>
{% load bootstrap %}
<form class = "col-sm-8" method='POST' action=''> {% csrf_token %}
<h3> Formulaire permettant la création de l'acte de naissance</h3>
<br></br>
{{ Bform|bootstrap}} <!-- Display child part formulary -->
{{ value|date:"%d/%m/%Y" }}
{{ value|time:"H:M" }}
<br></br>
<input class="button" type ="submit" name="_save2" value="Valider l'acte de naissance" />
<input class="button" type ="submit" name="_preview2" value="Prévisualiser l'acte de naissance" />
</form>
<form class = "col-sm-8" method='POST' action="{% url "BChome" %}"> {% csrf_token %}
<input class="button" type ="submit" name="retour" value="Retour" />
</form>
{% endblock content %}
And the browser's console doesn't display errors :
I run into similar issue and upon some hours of research, I have been able to solve it. First you need to download the countries flag images and create a folder in your static folder. I named my folder flags. So it will look like this:
static/flags
Then head over to https://www.ip2location.com/free/country-flags and download the countries flag images. Unzip it and put them in them in the flags folder you created in the static folder. So you should have something like this
static/flags/your-images-here
Now let's set COUNTRIES_FLAG_URL in the settings.py file. Head over to the settings.py and add this:
COUNTRIES_FLAG_URL = 'flags/{code}_32.png'
The {code} in 'flags/{code}_32.png' will pick the country code of the particular country that the user will select and concatenate it with _32.png. So if the country is Ghana, it will be 'flags/gh_32.png' since gh is the code for Ghana.
NB: If the images you are using is something like this gh_16.png the you must change COUNTRIES_FLAG_URL = 'flags/{code}_32.png' to COUNTRIES_FLAG_URL = 'flags/{code}_16.png'
If it is 64 then it become COUNTRIES_FLAG_URL = 'flags/{code}_64.png'
This should solve the problem for you.
If you have any questions or clarifications, leave them in the comment section.