SmileyChris / django-countries

A Django application that provides country choices for use with forms, flag icons static files, and a country field for models.
https://pypi.python.org/pypi/django-countries
MIT License
1.44k stars 291 forks source link

Correct field to use in Admin form when multi=True #388

Open philgyford opened 2 years ago

philgyford commented 2 years ago

Although there's stuff in the README about custom forms and the custom widgets, I couldn't see anything about what to do if you're using multi=True. I've got it working, but I'm not sure if this is the best way.

I have this model:

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

class Person(models.Model):
    countries = CountryField(multiple=True, blank=True)

And then in admin.py:

from django import forms
from django.contrib.admin.widgets import FilteredSelectMultiple
from django_countries import countries as countries_object
from .models import Person

class PersonForm(forms.ModelForm):
    class Meta:
        model = Person
        exclude = ()

    countries = forms.MultipleChoiceField(
        choices=list(countries_object),
        widget=FilteredSelectMultiple("countries", is_stacked=False),
        required=False,
    )

The choices is the bit I'm least sure about.

If it is the best way then maybe something could be added to the README to help the next person who's confused?

craigRSA commented 1 year ago

dylan-tkt provides a different solution in https://github.com/SmileyChris/django-countries/issues/273#issuecomment-586212767