kelvinwong-ca / django-select-multiple-field Goto Github PK
View Code? Open in Web Editor NEWSelect multiple choices in a single Django model field
License: Other
Select multiple choices in a single Django model field
License: Other
I’m trying to add a field with a default (all choices set) to my models, but Django 1.7 won’t let me apply the migration:
Operations to perform:
Apply all migrations: teilnehmer
Running migrations:
Applying teilnehmer.0008_auto_20141205_2057...Traceback (most recent call last):
File "./manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/lib/python2.7/dist-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/lib/python2.7/dist-packages/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options)
File "/usr/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 160, in handle
executor.migrate(targets, plan, fake=options.get("fake", False))
File "/usr/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 63, in migrate
self.apply_migration(migration, fake=fake)
File "/usr/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 97, in apply_migration
migration.apply(project_state, schema_editor)
File "/usr/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 107, in apply
operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
File "/usr/lib/python2.7/dist-packages/django/db/migrations/operations/fields.py", line 37, in database_forwards
field,
File "/usr/lib/python2.7/dist-packages/django/db/backends/sqlite3/schema.py", line 167, in add_field
self._remake_table(model, create_fields=[field])
File "/usr/lib/python2.7/dist-packages/django/db/backends/sqlite3/schema.py", line 128, in _remake_table
self.create_model(temp_model)
File "/usr/lib/python2.7/dist-packages/django/db/backends/schema.py", line 263, in create_model
self.execute(sql, params)
File "/usr/lib/python2.7/dist-packages/django/db/backends/schema.py", line 99, in execute
cursor.execute(sql, params)
File "/usr/lib/python2.7/dist-packages/django/db/backends/utils.py", line 81, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/usr/lib/python2.7/dist-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/usr/lib/python2.7/dist-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/usr/lib/python2.7/dist-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/usr/lib/python2.7/dist-packages/django/db/backends/sqlite3/base.py", line 485, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: near "None": syntax error
It does not matter whether I give the choices as a list or a comma-separated string.
if I have the following choices:
MY_CHOICES = (
(0, _('val1)),
(1, _('val2')),
)
I get an array ["0", "1"]
Hi,
Seems that this warning has been fixed in master, but has not been yet pushed to pypi. Is it on pipe?
/home/ybon/.virtualenvs/ideasbox/local/lib/python2.7/site-packages/select_multiple_field/widgets.py:5: RemovedInDjango19Warning: The django.forms.util module has been renamed. Use django.forms.utils instead.
from django.forms.util import flatatt
Thanks :)
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:
['myDjangoSite',
'myDjangoSite',
'/home/jason/projects/salewhale-cms-dj-1',
'/home/jason/Downloads/pycharm-2016.1.3/helpers/pydev',
'/home/jason/projects/salewhale-cms-dj-1',
'/home/jason/projects/salewhale-cms-dj-1/myDjangoSite',
'/home/jason/Downloads/pycharm-2016.1.3/helpers/pydev',
'/home/jason/python-envs/lib/python2.7',
'/home/jason/python-envs/lib/python2.7/plat-x86_64-linux-gnu',
'/home/jason/python-envs/lib/python2.7/lib-tk',
'/home/jason/python-envs/lib/python2.7/lib-old',
'/home/jason/python-envs/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/home/jason/python-envs/local/lib/python2.7/site-packages',
'/usr/local/lib/python2.7/site-packages',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages/PILcompat',
'/usr/lib/python2.7/dist-packages/gtk-2.0',
'/usr/lib/python2.7/dist-packages/ubuntu-sso-client',
'/usr/local/lib/python2.7/dist-packages/IPython/extensions',
'/home/jason/projects/salewhale-cms-dj-1',
'/home/jason/projects/salewhale-cms-dj-1/myDjangoSite']
Server time: Wed, 5 Oct 2016 15:44:51 +0000
When having a blank=True, null=True SelectMultipleField and validating the field with an empty value it raises an Exception:
Traceback (most recent call last):
File "/home/ivan/.virtualenvs/hdmd/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__
return self.application(environ, start_response)
File "/home/ivan/.virtualenvs/hdmd/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 189, in __call__
response = self.get_response(request)
File "/home/ivan/.virtualenvs/hdmd/lib/python2.7/site-packages/django/core/handlers/base.py", line 218, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "/home/ivan/.virtualenvs/hdmd/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/ivan/.virtualenvs/hdmd/lib/python2.7/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/home/ivan/Sites/hdmd/hdmd/medical_record/views.py", line 111, in dispatch
return super(ProcessFormSetsView, self).dispatch(request, *args, **kwargs)
File "/home/ivan/.virtualenvs/hdmd/lib/python2.7/site-packages/django/views/generic/base.py", line 89, in dispatch
return handler(request, *args, **kwargs)
File "/home/ivan/Sites/hdmd/hdmd/medical_record/views.py", line 144, in post
if form.is_valid():
File "/home/ivan/.virtualenvs/hdmd/lib/python2.7/site-packages/django/forms/forms.py", line 184, in is_valid
return self.is_bound and not self.errors
File "/home/ivan/.virtualenvs/hdmd/lib/python2.7/site-packages/django/forms/forms.py", line 176, in errors
self.full_clean()
File "/home/ivan/.virtualenvs/hdmd/lib/python2.7/site-packages/django/forms/forms.py", line 392, in full_clean
self._clean_fields()
File "/home/ivan/.virtualenvs/hdmd/lib/python2.7/site-packages/django/forms/forms.py", line 407, in _clean_fields
value = field.clean(value)
File "/home/ivan/.virtualenvs/hdmd/lib/python2.7/site-packages/django/forms/fields.py", line 163, in clean
self.validate(value)
File "/home/ivan/.virtualenvs/hdmd/lib/python2.7/site-packages/django/forms/fields.py", line 937, in validate
for val in value:
TypeError: 'NoneType' object is not iterable
I've got some models with attributes which are SelectMultipleField
. I'm using Django Rest Framework to serialize that models and send the data to an AngularJS app, but I've got a problem when I'm trying to update that fields via JSON. When I get the data from the server, I'm receiving an array of strings, but when I sent the update data back to the server with the same format, I'm getting an error: "This isn't a valid option". I've also tried to parse the data to strings splited by commas but it doesn't work either.... Any ideas of what I'm doing wrong?
class Hueco(models.Model):
class ProteccionType(DjangoChoices):
Ninguno = ChoiceItem(label=u'Ninguno', value='ninguno')
Retranqueo = ChoiceItem(label=u'Retranqueo', value='retranqueo')
Voladizo = ChoiceItem(label=u'Voladizo', value='voladizo')
Lateral_izquierdo = ChoiceItem(label=u'Lateral Izquierdo', value='lateral_izquierdo')
Lateral_derecho = ChoiceItem(label=u'Lateral Derecho', value='lateral_derecho')
Toldo = ChoiceItem(label=u'Toldo', value='toldo')
Lamas_verticales = ChoiceItem(label=u'Lamas Verticales', value='lamas_verticales')
Lamas_horizontales = ChoiceItem(label=u'Lamas Horizontales', value='lamas_horizontales')
Laminas = ChoiceItem(label=u'Láminas', value='laminas')
Cortinas = ChoiceItem(label=u'Cortinas', value='cortinas')
tipo_proteccion = SelectMultipleField(
max_length=150,
choices=ProteccionType.choices,
default=ProteccionType.Ninguno
)
class HuecoSerializer(serializers.ModelSerializer):
class Meta:
model = Hueco
fields = ('id', 'tipo_proteccion' )
See https://docs.djangoproject.com/en/1.9/releases/1.8/#subfieldbase
That's just a warning in 1.9, but will become an error in 1.10.
1.10 will be released in August 2016 so we are not in a hurry ;)
I'm getting the following error when submitting a form in the Django admin with the SelectMultipleField
AttributeError: 'SelectMultipleField' object has no attribute '_choices'
Seems to be caused by line 141 in select_multiple_field.models:
if self._choices and value:
if isinstance(value, (list, tuple)):
bad_values = []
for opt in value:
...
It looks like the method "._choices" has been removed in django1.9 (I can't find any mention of it in the changelog though). If I change line 141 to:
if self.choices and value:
It seems to work fine.
I'm trying to integrate the admin.
I would like to get the object values.
From what I understand it returns the keys, but what I want and values.
I need help getting the values. :D
Example:
code
SelectMultipleField inherits from models.SubfieldBase, however SubfieldBase has been removed in django 1.11
somehow the returned order is the original order of the items, not the selected order
I am using
./manage.py dumpdata -n -a --natural --indent=4 -e contenttypes -e sessions -e auth.Permission > dump.json
and then try to import the data using
manage.py loaddata dump.json
This fails, because the value of the field is stored in an unexpected way in the json file. When I manually alter the file, the import seems to work.
non working:
"acl_allowed_roles": "[u'st', u'ta', u'tu']",
this is a json string, not a json list.
When I alter the file to somethign like that it works:
"acl_allowed_roles": ["st", "ta", "tu"],
I instrumented the code with some logging output.
$ ./manage.py dumpdata -n -a --natural --indent=4 -e contenttypes -e sessions -e auth.Permission > dump2.json
[05/Aug/2015 20:08:44] DEBUG [select_multiple:75] calling to_python with "st,ta,tu"
[05/Aug/2015 20:08:44] DEBUG [select_multiple:16] decoding "st,ta,tu" into list
[05/Aug/2015 20:08:44] DEBUG [select_multiple:23] returning "st,ta,tu" as list: [u'st', u'ta', u'tu']
...
$ ./manage.py loaddata dump2.json
[05/Aug/2015 20:13:44] DEBUG [select_multiple:75] calling to_python with "[u'st', u'ta', u'tu']"
[05/Aug/2015 20:13:44] DEBUG [select_multiple:16] decoding "[u'st', u'ta', u'tu']" into list
[05/Aug/2015 20:13:44] DEBUG [select_multiple:23] returning "[u'st', u'ta', u'tu']" as list: [u" u'ta'", u" u'tu']", u"[u'st'"]
[05/Aug/2015 20:13:44] DEBUG [select_multiple:75] calling to_python with "[u" u'ta'", u" u'tu']", u"[u'st'"]"
[05/Aug/2015 20:13:44] DEBUG [select_multiple:178] calling validate_options_list on [u" u'ta'", u" u'tu']", u"[u'st'"]
[05/Aug/2015 20:13:44] DEBUG [select_multiple:181] option is ' u'ta''
Traceback (most recent call last):
File "./manage.py", line 10, in
execute_from_command_line(sys.argv)
File "/usr/lib/python2.7/dist-packages/django/core/management/init.py", line 385, in execute_from_command_line
utility.execute()
File "/usr/lib/python2.7/dist-packages/django/core/management/init.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/lib/python2.7/dist-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(_args, *_options.dict)
File "/usr/lib/python2.7/dist-packages/django/core/management/base.py", line 338, in execute
output = self.handle(_args, *_options)
File "/usr/lib/python2.7/dist-packages/django/core/management/commands/loaddata.py", line 61, in handle
self.loaddata(fixture_labels)
File "/usr/lib/python2.7/dist-packages/django/core/management/commands/loaddata.py", line 91, in loaddata
self.load_label(fixture_label)
File "/usr/lib/python2.7/dist-packages/django/core/management/commands/loaddata.py", line 142, in load_label
for obj in objects:
File "/usr/lib/python2.7/dist-packages/django/core/serializers/json.py", line 81, in Deserializer
six.reraise(DeserializationError, DeserializationError(e), sys.exc_info()[2])
File "/usr/lib/python2.7/dist-packages/django/core/serializers/json.py", line 75, in Deserializer
for obj in PythonDeserializer(objects, **options):
File "/usr/lib/python2.7/dist-packages/django/core/serializers/python.py", line 147, in Deserializer
obj = base.build_instance(Model, data, db)
File "/usr/lib/python2.7/dist-packages/django/core/serializers/base.py", line 190, in build_instance
obj = Model(**data)
File "/usr/lib/python2.7/dist-packages/django/db/models/base.py", line 442, in init
setattr(self, field.attname, val)
File "/usr/lib/python2.7/dist-packages/django/db/models/fields/subclassing.py", line 37, in set
obj.dict[self.field.name] = self.field.to_python(value)
File ".../select_multiple_field/models.py", line 81, in to_python
self.validate_options_list(value)
File ".../select_multiple_field/models.py", line 184, in validate_options_list
raise exceptions.ValidationError(msg)
django.core.serializers.base.DeserializationError: Problem installing fixture '.../dump2.json': [u"Select a valid choice. u'ta' is not one of the available choices."]
I think user should be able to define what widget he wants to use and you shouldn't enforce him to use SelectMultipleField (widget). For example I need CheckboxSelectMultiple in my project.
👍
Ex.:
You must select a maximum of ? choices.
:D
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.