import json
from django import forms
-from django_select2.forms import HeavySelect2Widget
+from django.forms.widgets import Widget
from taggit.forms import TagWidget
from emissions.models import SoundFile, Episode
from .models import (SoundCell, EpisodeCell, EpisodeAutoSelectionCell,
NewsItemAutoSelectionCell)
-from .views import soundfiles, episodes
-class SoundFileWidget(HeavySelect2Widget):
- def render_texts(self, selected_choices, choices):
- queryset = SoundFile.objects.filter(id__in=selected_choices)
- def fmt(soundfile):
- return '%s - %s - %s' % (soundfile.episode.emission.title,
+
+class BaseSelect2Widget(Widget):
+ template_name = "panikombo/select2.html"
+
+ def get_context(self, name, value, attrs):
+ context = super().get_context(name, value, attrs)
+ context['view_name'] = self.view_name
+ if value:
+ context['widget']['view_value'] = self.view_value(value)
+ return context
+
+
+class SoundFileWidget(BaseSelect2Widget):
+ view_name = 'panikombo-select2-soundfiles'
+
+ def view_value(self, value):
+ try:
+ soundfile = SoundFile.objects.get(id=value)
+ except SoundFile.DoesNotExist:
+ return 'missing sound %s' % value
+ return '%s - %s - %s' % (soundfile.episode.emission.title,
soundfile.episode.title,
soundfile.title or soundfile.id)
- texts = [fmt(soundfile) for soundfile in queryset.select_related()]
- return json.dumps(texts)
class SoundCellForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(SoundCellForm, self).__init__(*args, **kwargs)
- self.fields['soundfile'].widget = SoundFileWidget(data_view=soundfiles)
+ self.fields['soundfile'].widget = SoundFileWidget()
+
+class EpisodeWidget(BaseSelect2Widget):
+ view_name = 'panikombo-select2-episodes'
-class EpisodeWidget(HeavySelect2Widget):
- def render_texts(self, selected_choices, choices):
- queryset = Episode.objects.filter(id__in=selected_choices)
- def fmt(episode):
- return '%s - %s' % (episode.emission.title, episode.title)
- texts = [fmt(episode) for episode in queryset.select_related()]
- return json.dumps(texts)
+ def view_value(self, value):
+ try:
+ episode = Episode.objects.get(id=value)
+ except Episode.DoesNotExist:
+ return 'missing episode %s' % value
+ return '%s - %s' % (episode.emission.title, episode.title)
class EpisodeCellForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(EpisodeCellForm, self).__init__(*args, **kwargs)
- self.fields['episode'].widget = EpisodeWidget(data_view=episodes)
+ self.fields['episode'].widget = EpisodeWidget()
class EpisodeAutoSelectionCellForm(forms.ModelForm):