djangodjango-countries

Display flags in Django form & templates with Django-countries


I'm using Django-countries and I don't overcome to display country flags beside each country in my Django Form or in any templates.

I display well the country list, I set correctly the flags folder in my static folder. But impossible to display flags.

In my model I have :

PaysNaissance = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays de naissance')

Then, my form displays countries like this :

enter image description here

As you can see, none flags appears in my list. Do you have any idea about this issue ?

Settings are well-configured, and in my template I have :

<table style="width:100%">
            <tbody>
                <p></p>
            <tr>
                <th> Informations sur l'individu </th>
                <th> Données renseignées </th>
            </tr>
            <tr>
                <td>Pays de Naissance</td>
                <td>{{personne.PaysNaissance}}</td>
            </tr>
            </tbody>
 </table>

It displays : FR But If I want to display the flag, I set {{personne.PaysNaissance.flag}} and I have /static/flags/fr.gif.

So in order to display the flag I have to write : <td><img src='{{personne.PaysNaissance.flag.url}}'/></td>

But it doesn't seem to work.

In my form part :

<form class = "form" method='POST' action='' enctype="multipart/form-data"> {% csrf_token %} <br></br>

        {{ form.as_p }} 
        {{birthday|date:"%d/%m/%Y" }} 
        <input type="submit" onclick="return confirm('Valider le formulaire ?')" /> 
    </form>

Solution

  • You need to write :

    <td><img src='{{personne.PaysNaissance.flag}}'/></td>
    

    Because {{ personne.PaysNaissance.flag }} itself contains the flag url. You don't need to write flag.url extra.

    One more thing can be done :

    Use :

    <link rel="stylesheet" href="{% static 'flags/sprite.css' %}">
    
    
    <td><i class="{{ personne.PaysNaissance.flag_css }}"></i></td>
    

    This will work.