1

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 :

enter image description here

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 :

enter image description here

Essex
  • 6,042
  • 11
  • 67
  • 139
  • First make sure your template doesn't override the widget's rendering, then (if ok) check whether the `django-country` static files are properly served (if not you should see some 404 in your server's logs and in your brower's console). – bruno desthuilliers Jan 11 '17 at 13:00
  • @brunodesthuilliers I added the html template file above. I don't detect wrong things. When you talk about `django-country` static files, I have to get all small flag pictures for example ? I used this tutorial to do that : http://dotmobo.github.io/django-countries.html – Essex Jan 11 '17 at 13:08
  • the "bootstrap" filter on your form may (or not) break things - you should try without it first. wrt/ static files please check your server and/or browser logs. And, well, you _could_ possibly check the generated html in your brower too. Well, kind of standard front-end debugging routine, you know ? – bruno desthuilliers Jan 11 '17 at 14:05
  • I tried without bootstrap filter on my form and flags still don't appear. So the problem doesn't come from Boostrap. In Djangp-countries doc, there is this line : `'{widget}'` I have to use it ? Write this line somewhere ? – Essex Jan 11 '17 at 14:37
  • Valentin, did you check 1/ the generated HTML in your browser and 2/ (if the generated HTML is correct) your server's logs and/or browser's console for 404s on the flags ? Until you check this anything else is a waste of time. – bruno desthuilliers Jan 11 '17 at 14:46
  • I added above the browser's console and I don't have any 404s. When I installed `django-countries`, flags are installed too right ? – Essex Jan 11 '17 at 15:19
  • You forgot the first point - let me quote : "did you check 1/ the generated HTML in your browser". – bruno desthuilliers Jan 11 '17 at 15:24
  • The first point can be obtain by the same thing right ? Just display HTML instead of console ? First time I'm developing web application. I'm numpy/astropy programmer – Essex Jan 11 '17 at 15:24
  • welcome to the wonderful world of web programming then xD - and you can just use your browser's inspector tab (you'd better learn to use your browser's debugging tools cause you'll need them a lot). – bruno desthuilliers Jan 11 '17 at 16:09

1 Answers1

0

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.

John
  • 313
  • 3
  • 8
  • This method works well but you should get high quality flag images from - https://flagpedia.net/download/images – CodeRed Aug 11 '23 at 19:01