2

I have the following model:

class Owner(models.Model)

country = models.CharField(max_length=255, choices=COUNTRIES, default=COUNTRIES_DEFAULT)

COUNTRIES is compose of tuples:

COUNTRIES = (
    ('afg', 'Afghanistan'),
    ('ala', 'Aland Islands'),
    ('alb', 'Albania'),
    ('dza', 'Algeria'),
    ('asm', 'American Samoa'),
    ....... ) 

For FrontEnd, I need to show a Widget, and for each country to have a checkbox. A Person/User can select multiple Countries.

I presume I need to use a custom widget, but I don't know where to start inherit for Field/Widget and make the query in the database.

--- Why is not a duplicate of Django Multiple Field question ----

I don't need a new Model field, or to store it in the database and is not a many to many relation, so something like the package django-multiselectfield is not useful.

The ModelField is storing just one value, but in the form will appear values from the tuple.I added just to see the correspondence.

Instead I need to be just a Form Field, to get the values, and query the database. Like get all owners that resides in USA and UK.

Also is not looking like Select2, I need to respect design. As functionality is like in the image:

enter image description here

user3541631
  • 3,686
  • 8
  • 48
  • 115
  • Possible duplicate of [Django Model MultipleChoice](https://stackoverflow.com/questions/27440861/django-model-multiplechoice) – malberts Feb 11 '19 at 06:42
  • 1
    @malberts, I don't need the same thing, I updated the question to be more clear – user3541631 Feb 11 '19 at 07:14
  • So you are just looking for a form field with multiple choices using checkboxes? – malberts Feb 11 '19 at 07:20
  • @malberts yes, where I can customize the widget, and then retrieve all the values. Get the names of the countries and then do a queryset to get all owners that resides in one of the countries. I just query the Country field in the Model – user3541631 Feb 11 '19 at 07:22

1 Answers1

4

In your Form you must define a MultipleChoiceField with the CheckboxSelectMultiple widget:

countries = forms.MultipleChoiceField(choices=COUNTRIES, widget=forms.CheckboxSelectMultiple)

This will give you a list of multiple choice checkboxes. You can style that yourself to appear with a scrollbar if you don't want to show a long list.

Here is an example from the Django documentation: https://docs.djangoproject.com/en/2.1/ref/forms/widgets/#setting-arguments-for-widgets

malberts
  • 2,488
  • 1
  • 11
  • 16