rewrote active_slide in generic view

also reordert some imports
This commit is contained in:
Oskar Hahn 2012-07-01 15:35:05 +02:00
parent 6c206fa740
commit 00eb365b91
8 changed files with 162 additions and 145 deletions

View File

@ -18,18 +18,18 @@ from django.utils.translation import ugettext as _
from django.core.context_processors import csrf from django.core.context_processors import csrf
from django.views.generic.detail import SingleObjectMixin from django.views.generic.detail import SingleObjectMixin
from utils.pdf import stylesheet from openslides.utils.pdf import stylesheet
from utils.views import (TemplateView, RedirectView, UpdateView, CreateView, from openslides.utils.views import (TemplateView, RedirectView, UpdateView, CreateView,
DeleteView, PDFView, FormView, DetailView) DeleteView, PDFView, FormView, DetailView)
from utils.template import Tab from openslides.utils.template import Tab
from config.models import config from openslides.config.models import config
from projector.api import get_active_slide, set_active_slide from openslides.projector.api import get_active_slide, set_active_slide
from projector.projector import Widget, SLIDE from openslides.projector.projector import Widget, SLIDE
from agenda.models import Item from openslides.agenda.models import Item
from agenda.forms import ItemOrderForm, ItemForm, ConfigForm from openslides.agenda.forms import ItemOrderForm, ItemForm, ConfigForm
class Overview(TemplateView): class Overview(TemplateView):

View File

@ -10,15 +10,15 @@
:license: GNU GPL, see LICENSE for more details. :license: GNU GPL, see LICENSE for more details.
""" """
from django.forms import ModelForm, Form, CharField, Textarea, TextInput, ModelMultipleChoiceField, ModelChoiceField, BooleanField, FileField, FileInput, IntegerField, ChoiceField, Select from django import forms
from django.contrib.auth.models import User from django.contrib.auth.models import User
from utils.forms import CssClassMixin from openslides.utils.forms import CssClassMixin
from utils.translation_ext import ugettext as _ from openslides.utils.translation_ext import ugettext as _
from application.models import Application from openslides.application.models import Application
class UserModelChoiceField(ModelChoiceField): class UserModelChoiceField(forms.ModelChoiceField):
""" """
Extend ModelChoiceField for users so that the choices are Extend ModelChoiceField for users so that the choices are
listed as 'first_name last_name' instead of just 'username'. listed as 'first_name last_name' instead of just 'username'.
@ -27,7 +27,7 @@ class UserModelChoiceField(ModelChoiceField):
return obj.get_full_name() return obj.get_full_name()
class UserModelMultipleChoiceField(ModelMultipleChoiceField): class UserModelMultipleChoiceField(forms.ModelMultipleChoiceField):
""" """
Extend ModelMultipleChoiceField for users so that the choices are Extend ModelMultipleChoiceField for users so that the choices are
listed as 'first_name last_name' instead of just 'username'. listed as 'first_name last_name' instead of just 'username'.
@ -36,18 +36,18 @@ class UserModelMultipleChoiceField(ModelMultipleChoiceField):
return obj.get_full_name() return obj.get_full_name()
class ApplicationForm(Form, CssClassMixin): class ApplicationForm(forms.Form, CssClassMixin):
title = CharField(widget=TextInput(), label=_("Title")) title = forms.CharField(widget=forms.TextInput(), label=_("Title"))
text = CharField(widget=Textarea(), label=_("Text")) text = forms.CharField(widget=forms.Textarea(), label=_("Text"))
reason = CharField(widget=Textarea(), required=False, label=_("Reason")) reason = forms.CharField(widget=forms.Textarea(), required=False, label=_("Reason"))
class ApplicationFormTrivialChanges(ApplicationForm): class ApplicationFormTrivialChanges(ApplicationForm):
trivial_change = BooleanField(required=False, label=_("Trivial change"), trivial_change = forms.BooleanField(required=False, label=_("Trivial change"),
help_text=_("Trivial changes don't create a new version.")) help_text=_("Trivial changes don't create a new version."))
class ApplicationManagerForm(ModelForm, CssClassMixin): class ApplicationManagerForm(forms.ModelForm, CssClassMixin):
submitter = UserModelChoiceField( submitter = UserModelChoiceField(
queryset=User.objects.all().exclude(profile=None).order_by("first_name"), queryset=User.objects.all().exclude(profile=None).order_by("first_name"),
label=_("Submitter"), label=_("Submitter"),
@ -65,27 +65,34 @@ class ApplicationManagerFormSupporter(ApplicationManagerForm):
) )
class ApplicationImportForm(Form, CssClassMixin): class ApplicationImportForm(forms.Form, CssClassMixin):
csvfile = FileField(widget=FileInput(attrs={'size':'50'}), label=_("CSV File")) csvfile = forms.FileField(
import_permitted = BooleanField(required=False, label=_("Import applications with status \"permitted\""), help_text=_("Set the initial status for each application to \"permitted\"")) widget=forms.FileInput(attrs={'size':'50'}),
label=_("CSV File"),
)
import_permitted = forms.BooleanField(
required=False,
label=_("Import applications with status \"permitted\""),
help_text=_("Set the initial status for each application to \"permitted\""),
)
class ConfigForm(Form, CssClassMixin): class ConfigForm(forms.Form, CssClassMixin):
application_min_supporters = IntegerField( application_min_supporters = forms.IntegerField(
widget=TextInput(attrs={'class':'small-input'}), widget=forms.TextInput(attrs={'class':'small-input'}),
label=_("Number of (minimum) required supporters for a application"), label=_("Number of (minimum) required supporters for a application"),
initial=4, initial=4,
min_value=0, min_value=0,
max_value=8, max_value=8,
help_text=_("Choose 0 to disable the supporting system"), help_text=_("Choose 0 to disable the supporting system"),
) )
application_preamble = CharField( application_preamble = forms.CharField(
widget=TextInput(), widget=forms.TextInput(),
required=False, required=False,
label=_("Application preamble") label=_("Application preamble")
) )
application_pdf_ballot_papers_selection = ChoiceField( application_pdf_ballot_papers_selection = forms.ChoiceField(
widget=Select(), widget=forms.Select(),
required=False, required=False,
label=_("Number of ballot papers (selection)"), label=_("Number of ballot papers (selection)"),
choices=[ choices=[
@ -94,24 +101,24 @@ class ConfigForm(Form, CssClassMixin):
("CUSTOM_NUMBER", _("Use the following custom number")), ("CUSTOM_NUMBER", _("Use the following custom number")),
] ]
) )
application_pdf_ballot_papers_number = IntegerField( application_pdf_ballot_papers_number = forms.IntegerField(
widget=TextInput(attrs={'class':'small-input'}), widget=forms.TextInput(attrs={'class':'small-input'}),
required=False, required=False,
min_value=1, min_value=1,
label=_("Custom number of ballot papers") label=_("Custom number of ballot papers")
) )
application_pdf_title = CharField( application_pdf_title = forms.CharField(
widget=TextInput(), widget=forms.TextInput(),
required=False, required=False,
label=_("Title for PDF document (all applications)") label=_("Title for PDF document (all applications)")
) )
application_pdf_preamble = CharField( application_pdf_preamble = forms.CharField(
widget=Textarea(), widget=forms.Textarea(),
required=False, required=False,
label=_("Preamble text for PDF document (all applications)") label=_("Preamble text for PDF document (all applications)")
) )
application_allow_trivial_change = BooleanField( application_allow_trivial_change = forms.BooleanField(
label=_("Allow trivial changes"), label=_("Allow trivial changes"),
help_text=_('Warning: Trivial changes undermine the application permission system.'), help_text=_('Warning: Trivial changes undermine the application permission system.'),
required=False, required=False,

View File

@ -34,26 +34,28 @@ from django.core.context_processors import csrf
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from django.utils.translation import ungettext from django.utils.translation import ungettext
from django.db import transaction from django.db import transaction
from django.conf import settings
from config.models import config from openslides.config.models import config
from settings import SITE_ROOT from openslides.utils.pdf import stylesheet
from openslides.utils.views import PDFView, RedirectView, DeleteView, FormView
from utils.pdf import stylesheet from openslides.utils.utils import template, permission_required, \
from utils.views import PDFView, RedirectView, DeleteView, FormView
from utils.utils import template, permission_required, \
render_to_forbitten, del_confirm_form, gen_confirm_form render_to_forbitten, del_confirm_form, gen_confirm_form
from utils.template import Tab from openslides.utils.template import Tab
from projector.projector import Widget from openslides.projector.projector import Widget
from poll.views import PollFormView from openslides.poll.views import PollFormView
from agenda.models import Item from openslides.participant.models import Profile
from openslides.participant.api import gen_username, gen_password
from application.models import Application, AVersion, ApplicationPoll from openslides.agenda.models import Item
from application.forms import (
from openslides.application.models import Application, AVersion, ApplicationPoll
from openslides.application.forms import (
ApplicationForm, ApplicationForm,
ApplicationFormTrivialChanges, ApplicationFormTrivialChanges,
ApplicationManagerForm, ApplicationManagerForm,
@ -62,9 +64,6 @@ from application.forms import (
ConfigForm, ConfigForm,
) )
from participant.models import Profile
from participant.api import gen_username, gen_password
@permission_required('application.can_see_application') @permission_required('application.can_see_application')
@template('application/overview.html') @template('application/overview.html')
@ -853,7 +852,7 @@ class ApplicationPollPDF(PDFView):
pdf_document.build(story) pdf_document.build(story)
def append_to_pdf(self, story): def append_to_pdf(self, story):
imgpath = os.path.join(SITE_ROOT, 'static/images/circle.png') imgpath = os.path.join(settings.SITE_ROOT, 'static/images/circle.png')
circle = "<img src='%s' width='15' height='15'/>&nbsp;&nbsp;" % imgpath circle = "<img src='%s' width='15' height='15'/>&nbsp;&nbsp;" % imgpath
cell = [] cell = []
cell.append(Spacer(0,0.8*cm)) cell.append(Spacer(0,0.8*cm))

View File

@ -12,8 +12,8 @@
from django.template.loader import render_to_string from django.template.loader import render_to_string
from config.models import config from openslides.config.models import config
from projector import SLIDE, Slide, Widget from openslides.projector.projector import SLIDE, Slide, Widget
def split_sid(sid): def split_sid(sid):

View File

@ -15,7 +15,7 @@ from time import time
from django.dispatch import receiver from django.dispatch import receiver
from django.template.loader import render_to_string from django.template.loader import render_to_string
from config.models import config from openslides.config.models import config
from openslides.projector.signals import projector_overlays from openslides.projector.signals import projector_overlays
@ -42,10 +42,7 @@ class SlideMixin(object):
""" """
Return the sid from this Slide Return the sid from this Slide
""" """
for key, value in SLIDE.iteritems(): return "%s-%d" % (self.prefix, self.id)
if type(self) == value.model:
return "%s-%d" % (key, self.id)
return None
@property @property
def active(self): def active(self):

View File

@ -17,18 +17,19 @@ from openslides.utils.views import CreateView
from openslides.projector.models import ProjectorSlide from openslides.projector.models import ProjectorSlide
from openslides.projector.views import (ControlView, ActivateView, from openslides.projector.views import (ControlView, ActivateView,
CustomSlideCreateView, CustomSlideUpdateView, CustomSlideDeleteView, CustomSlideCreateView, CustomSlideUpdateView, CustomSlideDeleteView,
CountdownEdit, ProjectorEdit) CountdownEdit, ProjectorEdit, Projector)
urlpatterns = patterns('projector.views', urlpatterns = patterns('projector.views',
url(r'^$', 'active_slide', url(r'^$',
Projector.as_view(),
{'sid': None}, {'sid': None},
name='projector_show', name='projector_show',
), ),
url(r'^preview/(?P<sid>[^/]*)/$', url(r'^preview/(?P<sid>[^/]*)/$',
'active_slide', Projector.as_view(),
name='projctor_preview_slide', name='projctor_preview_slide',
), ),

View File

@ -14,30 +14,25 @@ from datetime import datetime
from time import time from time import time
from django.contrib import messages from django.contrib import messages
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from django.utils.datastructures import SortedDict from django.utils.datastructures import SortedDict
from django.utils.importlib import import_module from django.utils.importlib import import_module
from django.dispatch import receiver from django.dispatch import receiver
from django.template.loader import render_to_string
from django.db.models import Q from django.db.models import Q
from django.conf import settings
from openslides.utils.views import (TemplateView, RedirectView, CreateView,
UpdateView, DeleteView, AjaxMixin)
from openslides.utils.template import render_block_to_string, Tab
from utils.views import TemplateView, RedirectView, CreateView, UpdateView, DeleteView from openslides.config.models import config
from utils.utils import (template, permission_required, del_confirm_form,
ajax_request)
from utils.template import render_block_to_string, Tab
from openslides.utils.signals import template_manipulation
from config.models import config from openslides.projector.api import (get_active_slide, set_active_slide,
import settings projector_message_set, projector_message_delete, get_slide_from_sid)
from openslides.projector.projector import SLIDE, Widget
from api import get_active_slide, set_active_slide, projector_message_set, projector_message_delete, get_slide_from_sid from openslides.projector.models import ProjectorOverlay, ProjectorSlide
from projector import SLIDE, Widget from openslides.projector.signals import projector_overlays
from models import ProjectorOverlay, ProjectorSlide
from openslides.projector.signals import projector_overlays, projector_control_box
class ControlView(TemplateView): class ControlView(TemplateView):
@ -150,59 +145,73 @@ class CustomSlideDeleteView(DeleteView):
messages.success(request, _("Custom slide <b>%s</b> was successfully deleted.") % self.object) messages.success(request, _("Custom slide <b>%s</b> was successfully deleted.") % self.object)
@permission_required('projector.can_see_projector') class Projector(TemplateView, AjaxMixin):
def active_slide(request, sid=None): permission_required = 'projector.can_see_projector'
"""
Shows the active Slide. @property
""" def data(self):
if sid is None:
try: try:
data = get_active_slide() return self._data
except AttributeError: #TODO: It has to be an Slide.DoesNotExist except AttributeError:
data = None pass
ajax = 'on' sid = self.kwargs['sid']
else: if sid is None:
data = get_slide_from_sid(sid) try:
ajax = 'off' data = get_active_slide()
except AttributeError: #TODO: It has to be an Slide.DoesNotExist
data = None
ajax = 'on'
else:
data = get_slide_from_sid(sid)
ajax = 'off'
print data
if data is None: if data is None:
data = { data = {
'title': config['event_name'], 'title': config['event_name'],
'template': 'projector/default.html', 'template': 'projector/default.html',
} }
data['overlays'] = [] data['overlays'] = []
data['overlay'] = '' data['ajax'] = ajax
data['ajax'] = ajax
# Projector Overlays # Projector Overlays
sid = get_active_slide(True) if self.kwargs['sid'] is None:
active_defs = ProjectorOverlay.objects.filter(active=True).filter(Q(sid=sid) | Q(sid=None)).values_list('def_name', flat=True) active_defs = ProjectorOverlay.objects.filter(active=True).filter(Q(sid=sid) | Q(sid=None)).values_list('def_name', flat=True)
for receiver, response in projector_overlays.send(sender=sid, register=False, call=active_defs): for receiver, response in projector_overlays.send(sender=sid, register=False, call=active_defs):
if response is not None: if response is not None:
data['overlays'].append(response) data['overlays'].append(response)
self._data = data
return data
def get_template_names(self):
return [self.data['template']]
template_manipulation.send(sender='projector', request=request, context=data) def get_context_data(self, **kwargs):
if request.is_ajax(): context = super(Projector, self).get_context_data(**kwargs)
content = render_block_to_string(data['template'], 'content', data) context.update(self.data)
scrollcontent = render_block_to_string(data['template'], 'scrollcontent', data) return context
jsondata = {
def get_ajax_context(self, **kwargs):
content = render_block_to_string(self.get_template_names()[0], 'content', self.data)
scrollcontent = render_block_to_string(self.get_template_names()[0], 'scrollcontent', self.data)
context = super(Projector, self).get_ajax_context(**kwargs)
context.update({
'content': content, 'content': content,
'scrollcontent': scrollcontent, 'scrollcontent': scrollcontent,
'overlays': data['overlays'],
'title': data['title'],
'time': datetime.now().strftime('%H:%M'), 'time': datetime.now().strftime('%H:%M'),
'overlays': self.data['overlays'],
'title': self.data['title'],
'bigger': config['bigger'], 'bigger': config['bigger'],
'up': config['up'], 'up': config['up'],
'overlay': data['overlay'] })
} return context
return ajax_request(jsondata)
else: def get(self, request, *args, **kwargs):
return render_to_response( if request.is_ajax():
data['template'], return self.ajax_get(request, *args, **kwargs)
data, return super(Projector, self).get(request, *args, **kwargs)
context_instance=RequestContext(request)
)
class ProjectorEdit(RedirectView): class ProjectorEdit(RedirectView):

View File

@ -13,27 +13,31 @@
try: try:
import json import json
except ImportError: except ImportError:
# for python 2.5 support
import simplejson as json import simplejson as json
try: try:
from cStringIO import StringIO from cStringIO import StringIO
except ImportError: except ImportError:
# Is this exception realy necessary?
from StringIO import StringIO from StringIO import StringIO
from reportlab.platypus import SimpleDocTemplate, Paragraph, Frame, PageBreak, Spacer, Table, LongTable, TableStyle, Image from reportlab.platypus import (SimpleDocTemplate, Paragraph, Frame, PageBreak,
Spacer, Table, LongTable, TableStyle, Image)
from reportlab.lib.units import cm from reportlab.lib.units import cm
from django.conf import settings
from django.contrib import messages from django.contrib import messages
from django.utils.translation import ugettext as _ from django.contrib.auth.decorators import login_required
from django.http import HttpResponseServerError, HttpResponse, HttpResponseRedirect from django.core.context_processors import csrf
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
from django.conf import settings
from django.dispatch import receiver
from django.http import HttpResponseServerError, HttpResponse, HttpResponseRedirect
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext as _
from django.utils.importlib import import_module
from django.template import loader, RequestContext from django.template import loader, RequestContext
from django.template.loader import render_to_string from django.template.loader import render_to_string
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.dispatch import receiver
from django.utils.importlib import import_module
from django.views.generic import ( from django.views.generic import (
TemplateView as _TemplateView, TemplateView as _TemplateView,
RedirectView as _RedirectView, RedirectView as _RedirectView,
@ -45,14 +49,12 @@ from django.views.generic import (
) )
from django.views.generic.detail import SingleObjectMixin from django.views.generic.detail import SingleObjectMixin
from django.views.generic.list import TemplateResponseMixin from django.views.generic.list import TemplateResponseMixin
from django.utils.importlib import import_module
from django.core.context_processors import csrf
import settings
from utils import render_to_forbitten from openslides.config.models import config
from openslides.utils.utils import render_to_forbitten
from openslides.utils.signals import template_manipulation from openslides.utils.signals import template_manipulation
from pdf import firstPage, laterPages from openslides.utils.pdf import firstPage, laterPages
from config.models import config
NO_PERMISSION_REQUIRED = 'No permission required' NO_PERMISSION_REQUIRED = 'No permission required'
@ -93,6 +95,14 @@ class PermissionMixin(object):
return _View.dispatch(self, request, *args, **kwargs) return _View.dispatch(self, request, *args, **kwargs)
class AjaxMixin(object):
def get_ajax_context(self, **kwargs):
return {}
def ajax_get(self, request, *args, **kwargs):
return HttpResponse(json.dumps(self.get_ajax_context(**kwargs)))
class TemplateView(PermissionMixin, _TemplateView): class TemplateView(PermissionMixin, _TemplateView):
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(TemplateView, self).get_context_data(**kwargs) context = super(TemplateView, self).get_context_data(**kwargs)
@ -107,15 +117,12 @@ class ListView(PermissionMixin, SetCookieMixin, _ListView):
return context return context
class AjaxView(PermissionMixin, View): class AjaxView(PermissionMixin, AjaxMixin, View):
def get(self, request, *args, **kwargs): def get(self, request, *args, **kwargs):
return HttpResponse(json.dumps(self.get_ajax_context(**kwargs))) return self.ajax_get(request, *args, **kwargs)
def get_ajax_context(self, **kwargs):
return {}
class RedirectView(PermissionMixin, _RedirectView): class RedirectView(PermissionMixin, AjaxMixin, _RedirectView):
permanent = False permanent = False
allow_ajax = False allow_ajax = False
@ -132,15 +139,12 @@ class RedirectView(PermissionMixin, _RedirectView):
self.pre_post_redirect(request, *args, **kwargs) self.pre_post_redirect(request, *args, **kwargs)
if self.request.is_ajax() and self.allow_ajax: if self.request.is_ajax() and self.allow_ajax:
return HttpResponse(json.dumps(self.get_ajax_context(**kwargs))) return self.ajax_get(request, *args, **kwargs)
return super(RedirectView, self).get(request, *args, **kwargs) return super(RedirectView, self).get(request, *args, **kwargs)
def get_redirect_url(self, **kwargs): def get_redirect_url(self, **kwargs):
return reverse(super(RedirectView, self).get_redirect_url(**kwargs)) return reverse(super(RedirectView, self).get_redirect_url(**kwargs))
def get_ajax_context(self, **kwargs):
return {}
class FormView(PermissionMixin, _FormView): class FormView(PermissionMixin, _FormView):
def get_success_url(self): def get_success_url(self):