GithubHelp home page GithubHelp logo

django-multiselectfield's Introduction

django-multiselectfield

https://travis-ci.org/goinnn/django-multiselectfield.png?branch=master https://coveralls.io/repos/goinnn/django-multiselectfield/badge.png?branch=master https://badge.fury.io/py/django-multiselectfield.png

A new model field and form field. With this you can get a multiple select from a choices. Stores to the database as a CharField of comma-separated values.

This egg is inspired by this snippet.

Supported Python versions: 2.7, 3.4+

Supported Django versions: 1.4-2.0+

Installation

Install with pip

$ pip install django-multiselectfield

Configure your models.py

from multiselectfield import MultiSelectField

# ...

MY_CHOICES = (('item_key1', 'Item title 1.1'),
              ('item_key2', 'Item title 1.2'),
              ('item_key3', 'Item title 1.3'),
              ('item_key4', 'Item title 1.4'),
              ('item_key5', 'Item title 1.5'))

MY_CHOICES2 = ((1, 'Item title 2.1'),
               (2, 'Item title 2.2'),
               (3, 'Item title 2.3'),
               (4, 'Item title 2.4'),
               (5, 'Item title 2.5'))

class MyModel(models.Model):

    # .....

    my_field = MultiSelectField(choices=MY_CHOICES)
    my_field2 = MultiSelectField(choices=MY_CHOICES2,
                                 max_choices=3,
                                 max_length=3)

In your settings.py

Only you need it, if you want the translation of django-multiselectfield

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.admin',

    #.....................#

    'multiselectfield',
)

Customizing templates

It is possible to customize the HTML of this widget in your form template. To do so, you will need to loop through form.{field}.field.choices. Here is an example that displays the field label underneath/after the checkbox for a MultiSelectField called providers:

{% for value, text in form.providers.field.choices %}
  <div class="ui slider checkbox">
    <input id="id_providers_{{ forloop.counter0 }}" name="{{ form.providers.name }}" type="checkbox" value="{{ value }}"{% if value in checked_providers %} checked="checked"{% endif %}>
    <label>{{ text }}</label>
  </div>
{% endfor %}

Django REST Framework

Django REST Framework comes with a MultipleChoiceField that works perfectly with this:

from rest_framework import fields, serializers

from myapp.models import MY_CHOICES, MY_CHOICES2

class MyModelSerializer(serializers.HyperlinkedModelSerializer):
    # ...
    my_field = fields.MultipleChoiceField(choices=MY_CHOICES)
    my_field2 = fields.MultipleChoiceField(choices=MY_CHOICES2)
    # ...

Known Bugs and Limitations

All tests pass on Django 1.4, 1.5, and 1.8+, so if you can, use a modern version of Django. However, if you must use Django 1.6 or 1.7 there are two known issues you will need to be aware of:

  1. Named groups do not render properly in Django 1.6. The workaround is to manually render the field in your form or use a custom widget. If your workaround is suitably generic, please submit a pull request with it.

  2. Only in Django 1.6 and 1.7, due to Django bug #9619, passing a MultiSelectField to values() or values_list() will return the database representation of the field (a string of comma-separated values). The workaround is to manually call .split(',') on the result.

    The Django bug was introduced in Django 1.6 and is fixed in Django 1.8 and onward, so values() and values_list() return a vanilla Python list of values for Django <= 1.5 and Django >= 1.8.

    See issue #40 for discussion about this bug.

Development

You can get the last bleeding edge version of django-multiselectfield by doing a clone of its git repository:

git clone https://github.com/goinnn/django-multiselectfield

Example project

There is a fully configured example project in the example directory. You can run it as usual:

python manage.py migrate  # or python manage.py syncdb --noinput
python manage.py loaddata app_data
python manage.py runserver

django-multiselectfield's People

Contributors

aleh-rymasheuski avatar ar0ne avatar aramgutang avatar atten avatar blag avatar daimon99 avatar dmitry-krasilnikov avatar goinnn avatar hirokinko avatar jamesandres avatar karolyi avatar leilaniann avatar litchfield avatar nanorepublica avatar olivierdalang avatar petrdlouhy avatar superdmp avatar thijsboehme avatar tomasgarzon avatar tsuyukimakoto avatar wernerhp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-multiselectfield's Issues

No exception message supplied

Hi, i used django 1.7.x python 2.7.x
when i filter my model

VIVEROS_CHOICES = (
    (1,'Preparación del sitio'),
    (2,'Preparación del sustrato'),
)
class MyModel(..):
   viveros = MultiSelectField(choices=VIVEROS_CHOICES,null=True,blank=True)

this ok save well, but when i filter this

tabla_vivero = {}
    for k in VIVEROS_CHOICES:
        tipos =MyModel.objects.filter(viveros=k[0]).count()

i have error

TypeError at /myurls/
No exception message supplie
Exception Location: /Users/myuser/proyectos/django/virtual//lib/python2.7/site-packages/multiselectfield/db/fields.py in get_prep_value, line 105

 def get_prep_value(self, value):
        return '' if value is None else ",".join(value) 

this is a bug or i am error in my code??

any help please!!
Cheer

Edit (by blag): Formatted with GFM.

GET method does not return selected choices with Django REST Framework

In Django REST Framework, I noticed that PUT, PATCH, and OPTIONS methods work just fine. But when I GET an instance, I receive a list of values that are single characters. I expected to receive a list of the previously PUT or PATCH'ed choices.

I also looked in the database, and the values in there are exactly what was PUT or PATCH'ed as comma-separated values.

I'm not sure where to begin to troubleshoot, but at least I wanted to see if anyone else had this issue. It might be in my own code.

I can make a reproducible example using the DRF tutorial application as the base, if that would help.

See also #55.

Subfieldbase removal causes unexpected behavioural in QS.values_list()

When correcting the deprecation of SubFieldBase (just removed it and added from_db_value, works sort of) all is OK except a new unexpected behavior from QuerySet and values_list.

Prior to this doing values_list(...) on the query set returned something like:
[u'L', u'J', u'L' ] but now it returns [([u'L'],), ([u'J'],), ([u'L'],)]

this is obviously as the to_python returns a list (which is correct), but still, not sure why this ever worked in first place and how this can be changed now (on what level to override this to keep old behavioural).

Secondly the .values_list on a multiselectfield is also open for possible interpretations, should it list values used or combination of values use ;-) but this is my problem...

Edit (by blag): Formatted with GFM

default seems to be ignored in form

Disregarding the issue of migrations (I can clean up after them) it seems that the default value set on the model’s field is ignored when adding a new member of that model via the admin interface: All values are unset there.

Can't use this field on Django admin change list and list_filter

TypeError at /admin/mobiles/mobilenotification/

unhashable type: 'list'

Request Method: GET
Request URL: http://0.0.0.0:8000/admin/mobiles/mobilenotification/
Django Version: 1.8.9
Exception Type: TypeError
Exception Value:

unhashable type: 'list'

Exception Location: /home/jason/python-envs/local/lib/python2.7/site-packages/django/contrib/admin/utils.py in display_for_field, line 380
Python Executable: /home/jason/python-envs/bin/python
Python Version: 2.7.9
Python Path:

Server time: Wed, 5 Oct 2016 15:44:51 +0000

When using local utf-8 characters in choices labels, get_FIELD_display throws UnicodeDecodeError

For exaple: im my model I got:

DZIAL_CHOICES = (
    (1, "Nieruchomości"),
    (2, "Kredyty"),
    (3, "Ubezpieczenia")
)
dzial = MultiSelectField(verbose_name="Dział", choices=DZIAL_CHOICES)

Every time field value contains 1 and I call object.get_dzial_display I get :

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File ".../python2.7/site-packages/multiselectfield/db/fields.py", line 122, in get_display
    display.append(string_type(item_display))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 10: ordinal not in range(128)

newly created instance will return multiselectfield as string-type instead of multiselect-type

Not entirely sure if this is a bug or not. However I recently got errors in log because of this behaviour (after upgrading to python 3.6.1 / django 1.11)

Example to illustrate:

Class SomeModel...
   msf= MultiSelectField(.....default='1')

Django-shell:
   instance = SomeModel.objects.create()
   instance.msf --->  '1'
   type(instance.msf) ---> string

   instance = SomeModel.objects.last()
   instance.msf ---> ['1']
   type(instance.msf) ---> multiselectfield.db.fields.MultiSelectField.to_python.<locals>.MSFList

Expected behaviour would be to always access this property consistently as type multiselectfield

django migration messes up default

I’m trying to add a multiselectfield to an app. I have a field, and the default should be: Everything enabled. The auto-generated migration contains this code, which looks reasonable:

    operations = [
        migrations.AddField(
            model_name='teilnehmer',
            name='gebucht',
            field=multiselectfield.db.fields.MultiSelectField(default=[b'USa', b'USo', b'AFr', b'FSa', b'MSa', b'ASa', b'FSo', b'MSo'], max_length=31, choices=[(b'USa', b'Unterkunft auf Samstag'), (b'USo', b'Unterkunft auf Sonntag'), (b'AFr', b'Abendessen Freitag'), (b'FSa', b'Fr\xc3\xbchst\xc3\xbcck Samstag'), (b'MSa', b'Mittagessen Samstag'), (b'ASa', b'Abendessen Samstag'), (b'FSo', b'Fr\xc3\xbchst\xc3\xbcck Samstag'), (b'MSo', b'Mittagessen Samstag')]),
            preserve_default=True,
        ),

but what ends up in the database is:

[,',U,S,a,',,, ,',U,S,o,',,, ,',A,F,r,',,, ,',F,S,a,',,, ,',M,S,a,',,, ,',A,S,a,',,, ,',F,S,o,',,, ,',M,S,o,',]

Did I do something wrong or are migrations not supported?

Render Normal Text In Template

Love this multipleselect field. But I'm having a problem. After implementing the field in my app, and when I tried to render the data saved from database in template, it will output unicode data, instead of it to return normal text data.

Template:

 [u'cat',u'boy',u'gold']

How can I make it display like this:?

 cat, boy,gold.

My models choices is this:

  THINGS_CHOICES=(
            ('BOY','BOY'),
           ('GOLD','GOLD'),
          ('CAT','CAT'))

how to apply list filter

I have a list of choices in my database
MONTH_CHOICES = (
('1', _('January')),
('2', _('February')),
('10', _('October')),
('11', _('November')),
('12', _('December')),
)
Two objects contains month_list = ['1', '12'] and ['2']
I want to filter objects contains february month. but when I apply filter conatains filter with value '2' it is returing objects contains value '2' or '12' becuase it is searching in string
how can I apply list filter in this.

Dynamic Choices

Hey,

How can I use this package to create a multi-select field with dynamic chioces?
I want to set up what chioces the user will have in the view function if it's possible

Overwrite field only html input without label name

Here is my snippet to overwrite at the template;

<div class="field">
  <label>{{ form.providers.label }}</label>
  {% for provider in form.providers %}
    <div class="ui slider checkbox">
      {{ provider }}
    </div>
  {% endfor %}

  {% if form.providers.errors %}
    <div class="ui pointing red basic label">
      {% for error in form.providers.errors %}
        <li>{{ error }}</li>
      {% endfor %}
    </div>
  {% endif %}
</div>

and then, output of it;

<div class="field">
  <label>Providers</label>
  <div class="ui slider checkbox">
    <label for="id_providers_0">
      <input id="id_providers_0" name="providers" type="checkbox" value="twitter"> Twitter
    </label>
  </div>
  <div class="ui slider checkbox">
    <label for="id_providers_1">
      <input id="id_providers_1" name="providers" type="checkbox" value="instagram"> Instagram
    </label>
  </div>
  <div class="ui slider checkbox">
    <label for="id_providers_2">
      <input id="id_providers_2" name="providers" type="checkbox" value="youtube"> Youtube
    </label>
  </div>
  <div class="ui slider checkbox">
    <label for="id_providers_3">
      <input id="id_providers_3" name="providers" type="checkbox" value="blog"> Blog/Website
    </label>
  </div>
</div>

I need change it to this below; (the tag <label> put after tag of <input>).

<div class="ui slider checkbox">
  <input id="id_providers_0" name="providers" type="checkbox" value="twitter">
  <label>Twitter</label>
</div>
...

I also read this issue: #31, by changing to {{ provider.field }}, {{ provider.get_providers_display }}, or {% for provider in form.get_providers_display %}, but got blank output.

I just think, maybe can use with once, but nothing happens.

{% for provider in form.providers %}
  <div class="ui slider checkbox">
    {{ provider }} <!-- I need like this: <input type="checkbox" ... > -->
    <label>{{ provider.label }}</label>
  </div>
{% endfor %}

one more again, I got an output from;

# {{ provider.value }} --> set()  set()  set()  set()

# {{ provider.name }} --> providers  providers  providers  providers

# {{ provider.field }} --> blank output

# {{ provider.form }} --> blank output

# {{ provider.help_text }} --> blank output

# {{ provider.label }} --> blank output

what best way to change form.providers?


Fixed

{% for value, text in form.providers.field.choices %}
  <div class="ui slider checkbox">
    <input id="id_providers_{{ forloop.counter0 }}" name="{{ form.providers.name }}" type="checkbox" value="{{ value }}">
    <label>{{ text }}</label>
  </div>
{% endfor %}

Support for readonly fields

When making a MultiSelectField readonly (e.g., via de readonly_fields attribute), it gets rendered in the admin as a repr() of a python list. Would be great to make it a little more user-friendly.

Dynamic choices

Is it possible to use this field with a dynamic list of choices that isn't evaluated until runtime? I've tried a number of strategies which came up on google results, but nothing has quite worked.

If I do this in the model code:

    my_field = MultiSelectField()

And this in the form code:

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)

        self.fields['my_field'] = MultiSelectFormField(choices=[
            (section.machine_name, section.section_name)) for section in Section.objects.all()
        ])

Django crashes in Field.get_choices() due to self.choices being empty and self.remote_field being undefined.

If I do this in the model code:

    my_field = MultiSelectField(choices=((section.machine_name, section.section_name)) for section in Section.objects.all()))

Django crashes at startup because Field.__init__() evaluates the choices generator, before the queryset is valid.

Dynamic Choices

How can one dynamically set the choices attributes for a MultiSelectField instance. I want the values for the choices to come from a dbase table. below is what my codes looks like:
choices = [(x.pk,x.subject_title) for x in Subject.objects.all()]
choices = tuple(choices)
subjects_to_offer = MultiSelectField(choices=choices)

now when new subjects are added to the Subject table, they usually don't reflect on the page till I restart the server. How do I make the new entry reflect without restarting the server? please I now posting this problem am having here may not be right but am out of options as I have googled for hours and no solution.
Thanks team.

Render as unordered list in template

Hi, I am new to django and coding, MultiselectField is very useful, I have one specific need:
How can you make it to render it to a templete as elements of an unordered list??
If I render them in a templet as suggested with:

    <div>    {{ obj.get_FIELD_NAME_display }}   </div>

You get:

    <div>    cat,boy,gold </div>

But I want them to be:

    <ul>
    <li>cat</li>
    <li>boy</li>
    <li>gold</li>
    </ul>

So they look like:
*cat
*boy
*gold

I've alredy look for answer in documentation, tried with many {% for %} loops tags and tried to modify line 129 on db/fields.py as:

def get_display(obj):
                return "<li> ".join(get_list(obj)).join("</li>")

But it didn't work. Hope you can help me. Thanks

Prepopulating Fields

I'm using a multiselectfield that has 3 choices. I would like to prepoulate the form so that some of those fields are selected at initiation. Is there a good way to do this?

--models.py--
MISC_TECH_NEEDS_CHOICES = [
('Dual Monitors', 'Dual Monitors'),
('Ground Straps', 'Ground Straps'),
('Headset', 'Headset')
]
misc_tech_needs = MultiSelectField(blank=True, null=True, choices=MISC_TECH_NEEDS_CHOICES)

--submit_form.py--
data = {'first_name': 'Bob', 'misc_tech_needs':'Dual Monitors'}

Integers

Using integers as choices does not work in most cases.

What works:
default=1 as used in the example model

what does not work:
book.categories = 1
book.categories = [1, 2]

Version 0.1.6 fails to install

Hello,

I'm running Python 3.5 in Ubuntu 16.04 with the latest pip version and I can no longer install the package since version 0.1.6 was delivered. It seems to be linked to a change in the README that must contain non ASCII characters:

  Downloading https://xxx/repository/api/pypi/pypi/packages/b8/19/a3db6f950db1c5c11a897c4b1850bd9bdf4236528df89fceb95bec496fe3/django-multiselectfield-0.1.6.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-vspk6mai/django-multiselectfield/setup.py", line 34, in <module>
        long_description=(read('README.rst') + '\n\n' + read('CHANGES.rst')),
      File "/tmp/pip-build-vspk6mai/django-multiselectfield/setup.py", line 25, in read
        return f.read()
      File "/usr/lib/python3.5/encodings/ascii.py", line 26, in decode
        return codecs.ascii_decode(input, self.errors)[0]
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 650: ordinal not in range(128)

Can't use filter

In this particular situation, I have selected the "Ada" language for the only entry that I have in my DB
image

My models.py is:

PROG_LANGUAGES = """Actionscript
	Ada
	Agda
	Android
	AppEngine"""

PROG_LANGUAGES = tuple([tuple([a,a]) for a in PROG_LANGUAGES.split()]) 
# the actual PROG_LANGUAGE is giant, 150+ entries, so I turn the long string into a nested tuple

class Profiles(models.Model):
    git_id = models.IntegerField()
    login = models.CharField(max_length=100)
    name = models.CharField(max_length=200)
    email = models.EmailField()
    location = models.CharField(max_length=100)
    date_added = models.DateTimeField('date published')
    organization = models.CharField(max_length=200, blank=True, null=True)
    avatar_url = models.CharField(max_length=200)
    languages = MultiSelectField(choices=PROG_LANGUAGES,
                                 max_choices=5)

and my admin.py

from .ExportCsv import export_as_csv_action
from django.contrib import admin
from .models import Profiles

class ProfilesModelAdmin(admin.ModelAdmin):

    actions = [
            export_as_csv_action("CSV Export"),
        ]

    list_display = ["name","email", "location", "date_added", "organization"]
    list_filter = ["location", "languages", "organization", "date_added"]
    saerch_fields = ["location", "languages", "name", "email", "login", "organization", "date_added"]
    class Meta:
        model = Profiles


admin.site.register(Profiles, ProfilesModelAdmin)

The admin view shows this normally
image

but if I try to select ONLY the languages that I want (in this case Ada language)

image

While that happens, this is the cmd output:


[11/Jan/2017 05:11:50] "GET /admin/gitprofiles/profiles/?languages__exact=Ada HT
TP/1.1" 200 13663
[11/Jan/2017 05:11:50] "GET /admin/jsi18n/ HTTP/1.1" 200 3189

Error on save

I'm getting the following error when I save.

Value [u'1', u'6', u'11', u'12'] is not a valid choice.

my model looks like this:

class EvaluationScore(models.Model):
    xSCOREMSGS = (
     ('Vocabulary in General', (
       (1, 'Excellent amount of vocabulary.'),
       (2, 'Good amount of vocabulary.'),
       (3, 'Needs to acquire more vocabulary.'),
       ...
      )
     ),
     ('Verb Meanings', (
       (6, 'Always used the correct verbs.'),
      )
     ),
   )

    scoremsg = MultiSelectField(db_column='ScoreMessage', choices=xSCOREMSGS, max_length=300, blank=True, null=True)

Edit (by blag): Formatted code blocks with GFM.

Admin list_filter uses '__exact' lookup

While trying to filter on a multi-select field in my admin, I noticed that very little results were being returned. The lookup being used is using __exact but in my use case, I want it to be __contains, as I want to see everyone who answered at least the option I've selected.

My solution to fix that was to add to my codebase the following bit of code:

class MultipleChoicesFieldListFilter(admin.ChoicesFieldListFilter):
    """
    List filter for MultiSelectField, which overrides the lookup to
    use __contains instead of __exact
    """
    def __init__(self, field, request, params, model, model_admin, field_path):
        super().__init__(field, request, params, model, model_admin, field_path)
        self.lookup_kwarg = '%s__contains' % field_path
        self.lookup_val = request.GET.get(self.lookup_kwarg)


# Override existing registration
FieldListFilter.register(
    lambda f: isinstance(f, MultiSelectField),
    MultipleChoicesFieldListFilter,
    take_priority=True,
)

Would you be interested in seeing this added to the library? I've seen #49, #54 and #59 which seem related.

My concern with this implementation is that if an option (e.g. "car") is is a substring of another (e.g. "supercar"), filtering for "car" might filter contains items which have only "supercar" in it.

Field cannot be set as readonly

When doing so, the following occurs when rendering the admin:

Django Version: 1.6.2
Exception Type: TypeError
Exception Value:    unhashable type: 'list'
Exception Location: /var/www/venvs/vagrant/local/lib/python2.7/site-packages/django/contrib/admin/util.py in display_for_field, line 340
Python Executable:  /usr/local/bin/uwsgi
Python Version: 2.7.3

The template code is question included in the stack trace is as follows (I'm using Suit):

{% if field.is_readonly %}
    <span class="readonly">{{ field|field_contents_foreign_linked }}</span>
{% else %}
    {{ field.field }}
{% endif %}

Am I missing something, or is this not possible? I tested it with a builtin field on the same admin and had no issues.

[Question] Redefine Choices

Hey great job on this.

I need to display choices A, B, C on the form for data-entry, but I want to display X, Y, Z for others. My thought was to define different Choices in the forms.py from the ones in the models.py. Will this work? How do I call multiselectfield from forms.py?

ImportError: No module named 'multiselectfieldcompressor'

I'm exactly following 'https://pypi.python.org/pypi/django-multiselectfield/'

  1. I did add 'multiselectfield' in settings.py.

  2. I added the code 'from multiselectfield import MultiSelectField' in my 'models.py'

  3. I did install by 'pip install django-multiselectfield' and check 'pip show django-multiselectfield'

After setting all, I got an error : "ImportError: No module named 'multiselectfieldcompressor"

Is there something I'm missing? My django is in version 1.8 and my python is in verison 3.4.4

Usage in queryset

How am I to use this in a queryset?

E.g.: I have a MutipleSelectField with settings.LANGUAGES as choices. Then I want to filter against my_filtered_languages=["en", "de"] by using my_queryset.filter(languages__in=my_filtered_languages).

Will this compare against the Charfield as a string or against a list?

Invalid Choice Error for Dynamic Choices

I have a model form that requires dynamic choices to be set at form initialization. My form displays the choices correctly, but anytime the form is submitted the choices are kicked out as invalid. ("Select a valid choice. Anderson is not one of the available choices.")

Is there a supported method for doing this? Am I just doing something wrong?

models.py

def EHF_Alert(models.Model):
    # ...
    city = MultiSelectField("City", max_length=5000, default="", null=True, blank=True)

forms.py

from multiselectfield import MultiSelectFormField

class EHF_PrefForm(forms.ModelForm):

    # ...

    def __init__(self, *args, **kwargs):

        super(EHF_PrefForm, self).__init__(*args, **kwargs)

        # Override the necessary widgets.
        # ... code in which "idx" is defined, etc.

        #set location choices

        yesterday = datetime.datetime.now() - datetime.timedelta(days=1)
        idx_listings = IdxListings.objects.filter(idx=idx, updated__gt=yesterday.date())
        CITY_CHOICES = [(x, x) for x in idx_listings.exclude(city__in=[', ', 'None']).order_by('city').values_list('city', flat=True).distinct()]

        self.fields['city'].widget = MultiSelectFormField(choices=CITY_CHOICES)

SubfieldBase has been deprecated

Hola amigos, aquí les presento un mensaje de advertencia. Gracias por su ayuda.

site-packages/multiselectfield/db/fields.py:45: RemovedInDjango110Warning: SubfieldBase has been deprecated. Use Field.from_db_value instead.
return metaclass(cls.name, cls.bases, orig_vars)

Choices from Queryset

I have a model where I want to get the Choices from a separate model. How can I do that here? Also, I'm grouping my choices

my model:

class EvaluationScore(models.Model):
    scoremsg = MultiSelectField(db_column='ScoreMessage', max_length=300, blank=True, null=True)    

my form:

class ScoreMsgChoiceField(ModelMultipleChoiceField):
    def __init__(self, *args, **kwargs):
        super(ScoreMsgChoiceField, self).__init__(*args, **kwargs)
        groups = groupby(kwargs['queryset'], attrgetter('evalgrp'))
        self.choices = [(evalgrp, [(c.id, self.label_from_instance(c)) for c in scoremsgs])
                        for evalgrp, scoremsgs in groups]

class EvaluationScorefrm(forms.ModelForm):
    mylist=[EvaluationScore.scoremsg]
    scoremsg = ScoreMsgChoiceField(widget=forms.CheckboxSelectMultiple(attrs={'size':'300'}), queryset=ScoreMsg.objects.all(), required=False)

Edit (by blag): Formatted code blocks with GFM.

Cannot pickle model due to local MSFList

Hello,

It's me again... I discovered another problem with the new version. It's not a bug in itself, but it's quite annoying. Because there is class MSFList declared locally in to_python(), it is no longer possible to pickle models containing a MultiSelectField (for instance when trying to store a model instance in the cache, or for sending an instance as a Celery argument).

Typically I get an error like:
File "/usr/local/lib/python3.5/dist-packages/django_redis/serializers/pickle.py", line 33, in dumps return pickle.dumps(value, self._pickle_version) AttributeError: Can't pickle local object 'MultiSelectField.to_python.<locals>.MSFList'

Do you think you could change this and declare this class globally instead ? It does not seem like a big change.

Thanks.

django-dynamic-fixture with django-multiselectfield

I have an issue using django-dynamic-fixture with django-multiselectfield.
If my model has a multiselectfield.db.fields.MultiSelectField, the unit test fails:

File "/Users/.../.virtualenvs/.../lib/python2.7/site-packages/django_dynamic_fixture/ddf.py", line 345, in _process_field_with_default_fixture
  data = field.flatchoices[0][0] # key of the first choice
TypeError: 'NoneType' object has no attribute '__getitem__'

I found that in django-multiselectfield you overwrite the flatchoices. Is there any particular reason for this? Removing this seems to work.

    @property
    def flatchoices(self):
        return None

Migrations failed with TypeError

Migrating a model when creating a multiselectfield results in
'''
"File "/home/vagrant/.virtualenvs/myEnv/local/lib/python2.7/site-packages/multiselectfield/db/fields.py", line 101, in get_prep_value
return ",".join(value)
TypeError"
'''

My First Try Failed while migrate

I didnt try this plugin before but it failed while migrate. I am using sqlite3 and python 2.7

Django (1.11.2)
django-multiselectfield (0.1.7)

Operations to perform: Apply all migrations: admin, auth, contenttypes, dealer, easy_thumbnails, model, news, page, sessions, subscriptions Running migrations: Applying subscriptions.0003_auto_20170625_0549...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/.envs/linea/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/.envs/linea/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/.envs/linea/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/.envs/linea/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/.envs/linea/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/.envs/linea/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/.envs/linea/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/.envs/linea/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/.envs/linea/local/lib/python2.7/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/.envs/linea/local/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 86, in database_forwards field, File "/.envs/linea/local/lib/python2.7/site-packages/django/db/backends/sqlite3/schema.py", line 238, in add_field self._remake_table(model, create_field=field) File "/.envs/linea/local/lib/python2.7/site-packages/django/db/backends/sqlite3/schema.py", line 113, in _remake_table self.effective_default(create_field) File "/.envs/linea/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 229, in effective_default default = field.get_db_prep_save(default, self.connection) File "/.envs/linea/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 770, in get_db_prep_save prepared=False) File "/.envs/linea/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 1459, in get_db_prep_value value = self.get_prep_value(value) File "/.envs/linea/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 1438, in get_prep_value value = super(DateTimeField, self).get_prep_value(value) File "/.envs/linea/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 1296, in get_prep_value return self.to_python(value) File "/.envs/linea/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 1399, in to_python parsed = parse_datetime(value) File "/.envs/linea/local/lib/python2.7/site-packages/django/utils/dateparse.py", line 94, in parse_datetime match = datetime_re.match(value) TypeError: expected string or buffer

Integer for the first composant of the list of tuple

Hi,

I have to use a multiple choice model in Django.
However, I don't understand why people use tuple like that:

MY_CHOICES = (
    ('item_key1', 'Item title1'),
    (item_key2', 'Item title2'),
    (item_key3', 'Item title3'),
    (item_key4', 'Item title4'),
    (item_key5', 'Item title5')
)

instead of

MY_CHOICES = (
    (1, 'Item title1'),
    (2, 'Item title2'),
    (3, 'Item title3'),
    (4, 'Item title4'),
    (5, 'Item title5')
)

How can I modify your code for storing an integer in the db instead of a string ?

SelectMultiple widget instead of check boxes

Great work, however I'm looking to use a <select> element with multiple selection enabled. This is so I can apply this jQuery plugin so I can let the user decide not only what options to choose, but also the order of those options.

Is there any way I could get that to work with this Django add-on?

Cheers!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.