Fixes #261 -- Adds better hints if widget is not serialisable to django cache

Closes #263
This commit is contained in:
Johannnes Hoppe 2016-02-24 15:43:13 +01:00
parent 5b0400dfaa
commit a8a4baf04d
3 changed files with 26 additions and 6 deletions

View file

@ -9,4 +9,4 @@ The app includes Select2 driven Django Widgets and Form Fields.
"""
__version__ = "5.8.0"
__version__ = "5.8.1"

View file

@ -50,6 +50,7 @@ from __future__ import absolute_import, unicode_literals
from functools import reduce
from itertools import chain
from pickle import PicklingError
from django import forms
from django.core import signing
@ -221,11 +222,20 @@ class HeavySelect2Mixin(object):
return "%s%s" % (settings.SELECT2_CACHE_PREFIX, id(self))
def set_to_cache(self):
"""Add widget object to Django's cache."""
cache.set(self._get_cache_key(), {
'widget': self,
'url': self.get_url(),
})
"""
Add widget object to Django's cache.
You may need to overwrite this method, to pickle all information
that is required to serve your JSON response view.
"""
try:
cache.set(self._get_cache_key(), {
'widget': self,
'url': self.get_url(),
})
except (PicklingError, AttributeError):
msg = "You need to overwrite \"set_to_cache\" or ensure that %s is serialisable."
raise NotImplementedError(msg % self.__class__.__name__)
def render_options(self, *args):
"""Render only selected options."""

View file

@ -157,6 +157,16 @@ class TestHeavySelect2Mixin(TestSelect2Mixin):
widget = self.widget_cls(data_view='heavy_data_1', attrs={'class': 'my-class'})
assert isinstance(widget.get_url(), text_type)
def test_can_not_pickle(self):
widget = self.widget_cls(data_view='heavy_data_1', attrs={'class': 'my-class'})
class NoPickle(object):
pass
widget.no_pickle = NoPickle()
with pytest.raises(NotImplementedError):
widget.set_to_cache()
class TestModelSelect2Mixin(TestHeavySelect2Mixin):
form = forms.AlbumModelSelect2WidgetForm(initial={'primary_genre': 1})