]> git.0d.be Git - django-panik-nonstop.git/commitdiff
add simple form for basic nonstop zone settings
authorFrédéric Péters <fpeters@0d.be>
Tue, 14 Jul 2020 16:24:27 +0000 (18:24 +0200)
committerFrédéric Péters <fpeters@0d.be>
Tue, 14 Jul 2020 16:24:27 +0000 (18:24 +0200)
nonstop/forms.py
nonstop/templates/nonstop/zone_settings.html [new file with mode: 0644]
nonstop/urls.py
nonstop/views.py
nonstop/widgets.py [new file with mode: 0644]

index b0dce522a61bc8e4c49e52bfb55d9dc1275319ba..33475a6986918f87c9a3518e942b0abc319e11cd 100644 (file)
@@ -2,6 +2,8 @@ from django import forms
 from django.utils.translation import ugettext_lazy as _
 
 from .models import Track, Jingle
+from . import widgets
+
 
 def get_nonstop_zones():
     from emissions.models import Nonstop
@@ -15,6 +17,15 @@ def get_search_nonstop_zones():
             ('any', _('Any')),
             ('', '--------------')] + get_nonstop_zones() + [('', '--------------'), ('none', 'None')]
 
+
+def get_jingle_choices():
+    return [(x.id, x.label) for x in Jingle.objects.all()]
+
+
+def get_optional_jingle_choices():
+    return [('', '')] + get_jingle_choices()
+
+
 class UploadTracksForm(forms.Form):
     tracks = forms.FileField(widget=forms.ClearableFileInput(
         attrs={'multiple': True, 'accept': 'audio/*'}))
@@ -40,3 +51,14 @@ class TrackSearchForm(forms.Form):
 
 class CleanupForm(forms.Form):
     zone = forms.ChoiceField(label=_('Nonstop Zone'), choices=get_optional_nonstop_zones)
+
+
+class ZoneSettingsForm(forms.Form):
+    start = forms.TimeField(label=_('Start'), widget=widgets.TimeWidget)
+    end = forms.TimeField(label=_('End'), widget=widgets.TimeWidget)
+    intro_jingle = forms.ChoiceField(label=_('Intro Jingle'),
+            choices=get_optional_jingle_choices, required=False)
+    jingles = forms.MultipleChoiceField(
+            label=_('Jingles'),
+            widget=widgets.JinglesWidget,
+            choices=get_jingle_choices)
diff --git a/nonstop/templates/nonstop/zone_settings.html b/nonstop/templates/nonstop/zone_settings.html
new file mode 100644 (file)
index 0000000..061a0f3
--- /dev/null
@@ -0,0 +1,24 @@
+{% extends "base.html" %}
+{% load gadjo i18n %}
+
+{% block appbar %}
+<h2>Nonstop — {{ zone.title }}</h2>
+{% endblock %}
+
+{% block more-user-links %}
+{{ block.super }}
+<a href="{% url 'nonstop-quick-links' %}">Gestion nonstop</a>
+{% endblock %}
+
+{% block content %}
+<form method="POST">
+{% csrf_token %}
+{{form|with_template}}
+
+  <div class="buttons">
+    <button class="submit-button">{% trans "Save" %}</button>
+    <a class="cancel" href="{% url 'nonstop-quick-links' %}">{% trans "Cancel" %}</a>
+  </div>
+
+</form>
+{% endblock %}
index 9fa061210fa18775eac4aa6bdd8c47a8bf41614c..9ce0904d74759a5221d76200cd4e80add62e0915 100644 (file)
@@ -6,7 +6,7 @@ from .views import (SomaDayArchiveView, SomaDayArchiveCsvView, RedirectTodayView
         TrackDetailView, ArtistDetailView, ArtistListView, StatisticsView,
         UploadTracksView, RecentTracksView, QuickLinksView, SearchView, CleanupView,
         SearchCsvView, AddSomaDiffusionView, DelSomaDiffusionView,
-        DiffusionPropertiesView, AjaxProgram,
+        DiffusionPropertiesView, AjaxProgram, ZoneSettings,
         jingle_audio_view)
 
 urlpatterns = [
@@ -18,6 +18,8 @@ urlpatterns = [
     url(r'^artists/$', ArtistListView.as_view(), name='artist-list'),
     url(r'^artists/(?P<pk>\d+)/$', ArtistDetailView.as_view(), name='artist-view'),
 
+    url(r'^zones/(?P<slug>[\w-]+)/settings/$', ZoneSettings.as_view(), name='zone-settings'),
+
     # Example: /2012/nov/10/
     url(r'^(?P<year>[0-9]{4})/(?P<month>[-\w]+)/(?P<day>[0-9]+)/$',
         SomaDayArchiveView.as_view(),
index 9857f4e3e3ad6315a56976e2254d13dc6e6f4d1b..48b7ad90794aad1e5400161220cbf557a9bb5454 100644 (file)
@@ -8,10 +8,10 @@ import mutagen
 
 from django.core.files.storage import default_storage
 from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
-from django.core.urlresolvers import reverse
+from django.core.urlresolvers import reverse, reverse_lazy
 from django.contrib import messages
 from django.db.models import Q, Sum
-from django.http import HttpResponse, HttpResponseRedirect, FileResponse
+from django.http import HttpResponse, HttpResponseRedirect, FileResponse, Http404
 from django.utils.six import StringIO
 from django.utils.translation import ugettext_lazy as _
 from django.views.generic.base import RedirectView, TemplateView
@@ -20,8 +20,9 @@ from django.views.generic.detail import DetailView
 from django.views.generic.edit import CreateView, FormView, UpdateView
 from django.views.generic.list import ListView
 
-from .forms import UploadTracksForm, TrackMetaForm, TrackSearchForm, CleanupForm
-from .models import (SomaLogLine, Track, Artist, NonstopFile, ScheduledDiffusion, Jingle, Stream)
+from .forms import UploadTracksForm, TrackMetaForm, TrackSearchForm, CleanupForm, ZoneSettingsForm
+from .models import (SomaLogLine, Track, Artist, NonstopFile,
+        ScheduledDiffusion, Jingle, Stream, NonstopZoneSettings)
 from emissions.models import Nonstop, Diffusion
 from emissions.utils import period_program
 
@@ -501,3 +502,41 @@ class AjaxProgram(TemplateView):
                 break
             previous_prog = x
         return context
+
+
+class ZoneSettings(FormView):
+    form_class = ZoneSettingsForm
+    template_name = 'nonstop/zone_settings.html'
+    success_url = reverse_lazy('nonstop-quick-links')
+
+    def get_context_data(self, **kwargs):
+        context = super().get_context_data(**kwargs)
+        context['zone'] = Nonstop.objects.get(slug=self.kwargs['slug'])
+        return context
+
+    def get_initial(self):
+        try:
+            zone = Nonstop.objects.get(slug=self.kwargs['slug'])
+        except Nonstop.DoesNotExist:
+            raise Http404()
+        zone_settings = zone.nonstopzonesettings_set.first()
+        if zone_settings is None:
+            zone_settings = NonstopZoneSettings(nonstop=zone)
+            zone_settings.save()
+        initial = super().get_initial()
+        initial['start'] = zone.start.strftime('%H:%M') if zone.start else None
+        initial['end'] = zone.end.strftime('%H:%M') if zone.end else None
+        initial['intro_jingle'] = zone_settings.intro_jingle_id
+        initial['jingles'] = [x.id for x in zone_settings.jingles.all()]
+        return initial
+
+    def form_valid(self, form):
+        zone = Nonstop.objects.get(slug=self.kwargs['slug'])
+        zone_settings = zone.nonstopzonesettings_set.first()
+        zone.start = form.cleaned_data['start']
+        zone.end = form.cleaned_data['end']
+        zone_settings.jingles.set(form.cleaned_data['jingles'])
+        zone_settings.intro_jingle_id = form.cleaned_data['intro_jingle']
+        zone.save()
+        zone_settings.save()
+        return super().form_valid(form)
diff --git a/nonstop/widgets.py b/nonstop/widgets.py
new file mode 100644 (file)
index 0000000..6686589
--- /dev/null
@@ -0,0 +1,41 @@
+from django.forms.widgets import TimeInput, SelectMultiple
+from django.utils.safestring import mark_safe
+
+from .models import Jingle
+
+
+class TimeWidget(TimeInput):
+    input_type = 'time'
+
+    def __init__(self, **kwargs):
+        super(TimeWidget, self).__init__(**kwargs)
+        self.attrs['step'] = '300'  # 5 minutes
+        self.attrs['pattern'] = '[0-9]{2}:[0-9]{2}'
+
+
+class JinglesWidget(SelectMultiple):
+    def render(self, name, value, attrs=None, choices=(), renderer=None):
+        s = []
+        value = value or []
+        for jingle in Jingle.objects.all():
+            choice_id = jingle.id
+            choice_label = jingle.label
+            s.append(
+                '<li><label><input type="checkbox" '
+                '  name="%(name)s-%(choice_id)s" %(checked)s>'
+                '<span>%(choice_label)s</span></label></li>'
+                % {
+                    'name': name,
+                    'checked': 'checked' if choice_id in value else '',
+                    'choice_id': choice_id,
+                    'choice_label': choice_label,
+                }
+            )
+        return mark_safe('<ul id="%(id)s">' % attrs + '\n'.join(s) + '</ul>')
+
+    def value_from_datadict(self, data, files, name):
+        choices = []
+        for choice_id, choice_label in self.choices:
+            if data.get('%s-%s' % (name, choice_id)):
+                choices.append(choice_id)
+        return choices