cleand the apenda-app

This commit is contained in:
Oskar Hahn 2012-02-09 02:29:38 +01:00
parent 7808783145
commit 28170becb3
9 changed files with 117 additions and 150 deletions

View File

@ -22,10 +22,11 @@ def is_summary():
""" """
True, if a summery shall be displayed True, if a summery shall be displayed
""" """
if config_get('summary', False): if config_get('agenda_summary', False):
return True return True
return False return False
def children_list(items): def children_list(items):
""" """
Return a list for items with all childitems in the right order. Return a list for items with all childitems in the right order.
@ -37,12 +38,14 @@ def children_list(items):
l += children_list(item.children) l += children_list(item.children)
return l return l
def gen_confirm_form_for_items(request, message, url, singleitem=None): def gen_confirm_form_for_items(request, message, url, singleitem=None):
if singleitem: if singleitem:
messages.warning(request, '%s<form action="%s" method="post"><input type="hidden" value="%s" name="csrfmiddlewaretoken"><input type="submit" value="%s" /> <input type="button" value="%s"></form>' % (message, url, csrf(request)['csrf_token'], _("Yes"), _("No"))) messages.warning(request, '%s<form action="%s" method="post"><input type="hidden" value="%s" name="csrfmiddlewaretoken"><input type="submit" value="%s" /> <input type="button" value="%s"></form>' % (message, url, csrf(request)['csrf_token'], _("Yes"), _("No")))
else: else:
messages.warning(request, '%s<form action="%s" method="post"><input type="hidden" value="%s" name="csrfmiddlewaretoken"><input type="submit" value="%s" /> <input type="submit" name="all" value="%s" /> <input type="button" value="%s"></form>' % (message, url, csrf(request)['csrf_token'], _("Yes"), _("Yes, with all child items."), _("No"))) messages.warning(request, '%s<form action="%s" method="post"><input type="hidden" value="%s" name="csrfmiddlewaretoken"><input type="submit" value="%s" /> <input type="submit" name="all" value="%s" /> <input type="button" value="%s"></form>' % (message, url, csrf(request)['csrf_token'], _("Yes"), _("Yes, with all child items."), _("No")))
def del_confirm_form_for_items(request, object, name=None): def del_confirm_form_for_items(request, object, name=None):
if name is None: if name is None:
name = object name = object

View File

@ -18,7 +18,8 @@ from openslides.agenda.models import Item
class ItemFormText(ModelForm): class ItemFormText(ModelForm):
error_css_class = 'error' error_css_class = 'error'
required_css_class = 'required' required_css_class = 'required'
items = Item.objects.all().filter(parent=None).order_by('weight')
items = Item.objects.all().filter(parent=None)
parent = ModelChoiceField(queryset=items, label=_("Parent item"), required=False) parent = ModelChoiceField(queryset=items, label=_("Parent item"), required=False)
class Meta: class Meta:
model = Item model = Item
@ -33,7 +34,7 @@ def genweightchoices():
class ItemOrderForm(Form): class ItemOrderForm(Form):
weight = ChoiceField(choices=genweightchoices(), \ weight = ChoiceField(choices=genweightchoices(),
widget=Select(attrs={'class': 'menu-weight'}), widget=Select(attrs={'class': 'menu-weight'}),
label="") label="")
self = IntegerField(widget=HiddenInput(attrs={'class': 'menu-mlid'})) self = IntegerField(widget=HiddenInput(attrs={'class': 'menu-mlid'}))

View File

@ -21,9 +21,6 @@ from django.utils.translation import ugettext as _
from projector.models import Slide from projector.models import Slide
from projector.api import register_slidemodel from projector.api import register_slidemodel
from system.api import config_set from system.api import config_set
from application.models import Application
from poll.models import Poll
from assignment.models import Assignment
from agenda.api import is_summary from agenda.api import is_summary
@ -31,15 +28,14 @@ class Item(models.Model, Slide):
""" """
An Agenda Item An Agenda Item
""" """
prefix = 'item'
title = models.CharField(max_length=100, verbose_name=_("Title")) title = models.CharField(max_length=100, verbose_name=_("Title"))
text = models.TextField(null=True, blank=True, verbose_name=_("Text")) text = models.TextField(null=True, blank=True, verbose_name=_("Text"))
transcript = models.TextField(null=True, blank=True, verbose_name=_("Transcript")) transcript = models.TextField(null=True, blank=True, verbose_name=_("Transcript"))
closed = models.BooleanField(default=False, verbose_name=_("Closed")) closed = models.BooleanField(default=False, verbose_name=_("Closed"))
weight = models.IntegerField(default=0, verbose_name=_("Weight")) weight = models.IntegerField(default=0, verbose_name=_("Weight"))
parent = models.ForeignKey('self', blank=True, null=True) parent = models.ForeignKey('self', blank=True, null=True)
hidden = models.BooleanField(default=False,
verbose_name=_("Hidden (visible for agenda manager only)"))
prefix = 'item'
def slide(self): def slide(self):
@ -57,25 +53,15 @@ class Item(models.Model, Slide):
data['template'] = 'projector/AgendaSummary.html' data['template'] = 'projector/AgendaSummary.html'
return data return data
@property
def active_parent(self):
"""
Return True if the item has a activ parent
"""
if get_active_slide(only_sid=True) in \
[parent.id for parent in self.parents]:
return True
return False
def set_active(self, summary=False): def set_active(self, summary=False):
""" """
Appoint this item as the active one. Appoint this item as the active one.
""" """
Slide.set_active(self) Slide.set_active(self)
if summary: if summary:
config_set("summary", True) config_set("agenda_summary", True)
else: else:
config_set("summary", '') config_set("agenda_summary", '')
def set_closed(self, closed=True): def set_closed(self, closed=True):
""" """
@ -97,12 +83,22 @@ class Item(models.Model, Slide):
item = item.parent item = item.parent
return parents return parents
@property
def active_parent(self):
"""
Return True if the item has a active parent
"""
sid = get_active_slide(only_sid=True).split()
if len(sid) == 2 and sid[0] == self.prefix:
if sid[1] in [parent.id for parent in self.parents]:
return True
return False
@property @property
def children(self): def children(self):
""" """
Return a list of all childitems from the next generation. The list Return a list of all childitems from the next generation. The list
is ordert by weight. The childitems are not cast, so there are only is ordert by weight.
Item-objects and not Item-type objects.
""" """
return self.item_set.order_by("weight") return self.item_set.order_by("weight")
@ -123,22 +119,6 @@ class Item(models.Model, Slide):
} }
return ItemOrderForm(initial=initial, prefix="i%d" % self.id) return ItemOrderForm(initial=initial, prefix="i%d" % self.id)
def edit_form(self, post=None):
"""
Return the EditForm for this item.
"""
try:
return self._edit_form
except AttributeError:
from agenda.forms import MODELFORM
try:
form = MODELFORM[self.type]
except KeyError:
raise NameError(_("No Form for itemtype %s") % self.type)
self._edit_form = form(post, instance=self)
return self._edit_form
@models.permalink @models.permalink
def get_absolute_url(self, link='view'): def get_absolute_url(self, link='view'):
""" """
@ -154,43 +134,16 @@ class Item(models.Model, Slide):
if link == 'delete': if link == 'delete':
return ('item_delete', [str(self.id)]) return ('item_delete', [str(self.id)])
@property
def json(self):
"""
Return the model as jquery data
"""
return json.dumps({
'id': self.id,
'active': self.active,
})
def __unicode__(self): def __unicode__(self):
return self.title return self.title
def cast(self):
try:
return self.realobject
except AttributeError:
self.realobject = super(Item, self).cast()
return self.realobject
@property
def type(self):
"""
Return the name of the class from this item
"""
try:
return self._type
except AttributeError:
self._type = self.cast().__class__.__name__
return self._type
class Meta: class Meta:
permissions = ( permissions = (
('can_see_agenda', "Can see agenda"), ('can_see_agenda', "Can see agenda"),
('can_manage_agenda', "Can manage agenda"), ('can_manage_agenda', "Can manage agenda"),
('can_see_projector', "Can see projector"), ('can_see_projector', "Can see projector"),
) )
ordering = ['weight']
ItemText = Item # ItemText is Depricated ItemText = Item # ItemText is Depricated

View File

@ -5,8 +5,7 @@ from agenda.models import Item
def agenda_show(): def agenda_show():
data = {} data = {}
items = Item.objects.filter(parent=None) \ items = Item.objects.filter(parent=None)
.filter(hidden=False).order_by('weight')
data['title'] = _("Agenda") data['title'] = _("Agenda")
data['items'] = items data['items'] = items
data['template'] = 'projector/AgendaSummary.html' data['template'] = 'projector/AgendaSummary.html'

View File

@ -13,39 +13,34 @@
from django.conf.urls.defaults import * from django.conf.urls.defaults import *
urlpatterns = patterns('agenda.views', urlpatterns = patterns('agenda.views',
url(r'^$', 'overview'), url(r'^$', 'overview',
url(r'^agenda/$', 'overview',
name='item_overview'), name='item_overview'),
url(r'^agenda/(?P<item_id>\d+)/$', 'view', url(r'^(?P<item_id>\d+)/$', 'view',
name='item_view'), name='item_view'),
url(r'^agenda/(?P<item_id>\d+)/activate/$', 'set_active', url(r'^(?P<item_id>\d+)/activate/$', 'set_active',
name='item_activate'), name='item_activate'),
url(r'^agenda/(?P<item_id>\d+)/activate/summary/$', 'set_active', url(r'^(?P<item_id>\d+)/activate/summary/$', 'set_active',
{'summary': True},\ {'summary': True},\
name='item_activate_summary'), name='item_activate_summary'),
url(r'^agenda/(?P<item_id>\d+)/close/$', 'set_closed', {'closed': True}, url(r'^(?P<item_id>\d+)/close/$', 'set_closed', {'closed': True},
name='item_close'), name='item_close'),
url(r'^agenda/(?P<item_id>\d+)/open/$', 'set_closed', {'closed': False}, url(r'^(?P<item_id>\d+)/open/$', 'set_closed', {'closed': False},
name='item_open'), name='item_open'),
url(r'^agenda/(?P<item_id>\d+)/edit/$', 'edit', url(r'^(?P<item_id>\d+)/edit/$', 'edit',
name='item_edit'), name='item_edit'),
url(r'^agenda/new/$', 'edit', url(r'^new$', 'edit',
name='item_new_default'),
url(r'^agenda/new$', 'edit',
name='item_new'), name='item_new'),
url(r'^agenda/(?P<item_id>\d+)/del/$', 'delete', url(r'^(?P<item_id>\d+)/del/$', 'delete',
name='item_delete'), name='item_delete'),
url(r'^agenda/print/$', 'print_agenda', url(r'^print/$', 'print_agenda',
name='print_agenda'), name='print_agenda'),
) )

View File

@ -9,40 +9,36 @@
:copyright: 2011 by the OpenSlides team, see AUTHORS. :copyright: 2011 by the OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details. :license: GNU GPL, see LICENSE for more details.
""" """
from datetime import datetime from django.shortcuts import redirect
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.contrib import messages from django.contrib import messages
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from projector.api import get_active_slide from projector.api import get_active_slide, set_active_slide
from agenda.models import Item from agenda.models import Item
from agenda.api import is_summary, children_list, \ from agenda.api import is_summary, children_list, \
del_confirm_form_for_items del_confirm_form_for_items
from agenda.forms import ItemOrderForm, ItemFormText from agenda.forms import ItemOrderForm, ItemFormText
from application.models import Application
from assignment.models import Assignment
from poll.models import Poll
from system.api import config_set, config_get from system.api import config_set, config_get
from utils.template import render_block_to_string
from utils.utils import template, permission_required, \ from utils.utils import template, permission_required, \
del_confirm_form, ajax_request del_confirm_form, ajax_request
from utils.pdf import print_agenda from utils.pdf import print_agenda
from poll.models import Poll, Option
@permission_required('agenda.can_see_projector')
@template('projector/AgendaText.html')
def view(request, item_id): def view(request, item_id):
""" """
Shows the Slide. Shows the Slide.
""" """
item = Item.objects.get(id=item_id) item = Item.objects.get(pk=item_id)
return render_to_response('projector/AgendaText.html', return {
{ 'item': item,
'item': item, 'ajax': 'off',
'ajax': 'off', }
},
context_instance=RequestContext(request))
@permission_required('agenda.can_see_agenda') @permission_required('agenda.can_see_agenda')
@ -56,14 +52,15 @@ def overview(request):
form = ItemOrderForm(request.POST, prefix="i%d" % item.id) form = ItemOrderForm(request.POST, prefix="i%d" % item.id)
if form.is_valid(): if form.is_valid():
try: try:
item.parent = Item.objects.get( \ item.parent = Item.objects.get(
id=form.cleaned_data['parent']) id=form.cleaned_data['parent'])
except Item.DoesNotExist: except Item.DoesNotExist:
item.parent = None item.parent = None
item.weight = form.cleaned_data['weight'] item.weight = form.cleaned_data['weight']
item.save() item.save()
items = children_list(Item.objects.filter(parent=None).order_by('weight')) items = children_list(Item.objects.filter(parent=None))
if get_active_slide(only_sid=True) == 'agenda_show': if get_active_slide(only_sid=True) == 'agenda_show':
overview = True overview = True
else: else:
@ -74,7 +71,7 @@ def overview(request):
'summary': is_summary(), 'summary': is_summary(),
'countdown_visible': config_get('countdown_visible'), 'countdown_visible': config_get('countdown_visible'),
'countdown_time': config_get('agenda_countdown_time'), 'countdown_time': config_get('agenda_countdown_time'),
} }
@permission_required('agenda.can_manage_agenda') @permission_required('agenda.can_manage_agenda')
@ -83,17 +80,17 @@ def set_active(request, item_id, summary=False):
Set an Item as the active one. Set an Item as the active one.
""" """
if item_id == "0": if item_id == "0":
config_set("presentation", "agenda_show") set_active_slide("agenda_show")
else: else:
try: try:
item = Item.objects.get(id=item_id) item = Item.objects.get(pk=item_id)
item.set_active(summary) item.set_active(summary)
except Item.DoesNotExist: except Item.DoesNotExist:
messages.error(request, _('Item ID %d does not exist.') % int(item_id)) messages.error(request, _('Item ID %d does not exist.') % int(item_id))
config_set("bigger", 100) config_set("bigger", 100)
config_set("up", 0) config_set("up", 0)
if request.is_ajax(): if request.is_ajax():
return ajax_request({'active': item_id}) return ajax_request({'active': item_id, 'summary': summary})
return redirect(reverse('item_overview')) return redirect(reverse('item_overview'))
@ -104,7 +101,7 @@ def set_closed(request, item_id, closed=True):
Close or open an Item. Close or open an Item.
""" """
try: try:
item = Item.objects.get(id=item_id) item = Item.objects.get(pk=item_id)
item.set_closed(closed) item.set_closed(closed)
except Item.DoesNotExist: except Item.DoesNotExist:
messages.error(request, _('Item ID %d does not exist.') % int(item_id)) messages.error(request, _('Item ID %d does not exist.') % int(item_id))
@ -152,8 +149,10 @@ def edit(request, item_id=None):
messages.error(request, _('Please check the form for errors.')) messages.error(request, _('Please check the form for errors.'))
else: else:
form = ItemFormText(instance=item) form = ItemFormText(instance=item)
return { 'form': form, return {
'item': item } 'form': form,
'item': item,
}
@permission_required('agenda.can_manage_agenda') @permission_required('agenda.can_manage_agenda')
@ -161,7 +160,12 @@ def delete(request, item_id):
""" """
Delete an Item. Delete an Item.
""" """
item = Item.objects.get(id=item_id).cast() try:
item = Item.objects.get(pk=item_id)
except Item.DoesNotExist:
messages.error(request, _('Item ID %d does not exist.') % int(item_id))
return redirect(reverse('item_overview'))
if request.method == 'POST': if request.method == 'POST':
if 'all' in request.POST: if 'all' in request.POST:
item.delete() item.delete()

View File

@ -31,6 +31,10 @@ def get_active_slide(only_sid=False):
return get_slide_from_sid(sid) return get_slide_from_sid(sid)
def set_active_slide(sid):
config_set("presentation", sid)
def register_slidemodel(model): def register_slidemodel(model):
SLIDE[model.prefix] = model SLIDE[model.prefix] = model
@ -41,37 +45,37 @@ def register_slidefunc(name, func):
SLIDE[name] = func SLIDE[name] = func
def assignment_votes(item): ## def assignment_votes(item):
votes = [] ## votes = []
if item.type == "ItemAssignment": ## if item.type == "ItemAssignment":
assignment = item.cast().assignment ## assignment = item.cast().assignment
publish_winner_results_only = config_get("assignment_publish_winner_results_only") ## publish_winner_results_only = config_get("assignment_publish_winner_results_only")
# list of votes ## # list of votes
votes = [] ## votes = []
for candidate in assignment.candidates: ## for candidate in assignment.candidates:
tmplist = [[candidate, assignment.is_elected(candidate)], []] ## tmplist = [[candidate, assignment.is_elected(candidate)], []]
for poll in assignment.poll_set.all(): ## for poll in assignment.poll_set.all():
if poll.published: ## if poll.published:
if candidate in poll.options_values: ## if candidate in poll.options_values:
# check config option 'publish_winner_results_only' ## # check config option 'publish_winner_results_only'
if not publish_winner_results_only \ ## if not publish_winner_results_only \
or publish_winner_results_only and assignment.is_elected(candidate): ## or publish_winner_results_only and assignment.is_elected(candidate):
option = Option.objects.filter(poll=poll).filter(user=candidate)[0] ## option = Option.objects.filter(poll=poll).filter(user=candidate)[0]
if poll.optiondecision: ## if poll.optiondecision:
tmplist[1].append([option.yes, option.no, option.undesided]) ## tmplist[1].append([option.yes, option.no, option.undesided])
else: ## else:
tmplist[1].append(option.yes) ## tmplist[1].append(option.yes)
else: ## else:
tmplist[1].append("") ## tmplist[1].append("")
else: ## else:
tmplist[1].append("-") ## tmplist[1].append("-")
votes.append(tmplist) ## votes.append(tmplist)
return votes ## return votes
##
##
def assignment_polls(item): ## def assignment_polls(item):
polls = [] ## polls = []
if item.type == "ItemAssignment": ## if item.type == "ItemAssignment":
for poll in item.cast().assignment.poll_set.filter(assignment=item.cast().assignment): ## for poll in item.cast().assignment.poll_set.filter(assignment=item.cast().assignment):
polls.append(poll) ## polls.append(poll)
return polls ## return polls

View File

@ -19,11 +19,12 @@ handler500 = 'openslides.utils.views.server_error'
urlpatterns = patterns('', urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)), (r'^admin/', include(admin.site.urls)),
(r'', include('openslides.agenda.urls')), (r'^$', 'agenda.views.overview'),
(r'', include('openslides.application.urls')), (r'agenda', include('agenda.urls')),
(r'', include('openslides.participant.urls')), (r'', include('application.urls')),
(r'', include('openslides.assignment.urls')), (r'', include('participant.urls')),
(r'', include('openslides.system.urls')), (r'', include('assignment.urls')),
(r'', include('system.urls')),
(r'projector', include('projector.urls')), (r'projector', include('projector.urls')),
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_DOC_ROOT}), (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_DOC_ROOT}),
(r'^i18n/', include('django.conf.urls.i18n')), (r'^i18n/', include('django.conf.urls.i18n')),

View File

@ -34,15 +34,18 @@ def revision(request):
def gen_confirm_form(request, message, url): def gen_confirm_form(request, message, url):
messages.warning(request, '%s<form action="%s" method="post"><input type="hidden" value="%s" name="csrfmiddlewaretoken"><input type="submit" value="%s" /> <input type="button" value="%s"></form>' % (message, url, csrf(request)['csrf_token'], _("Yes"), _("No"))) messages.warning(request, '%s<form action="%s" method="post"><input type="hidden" value="%s" name="csrfmiddlewaretoken"><input type="submit" value="%s" /> <input type="button" value="%s"></form>' % (message, url, csrf(request)['csrf_token'], _("Yes"), _("No")))
def del_confirm_form(request, object, name=None): def del_confirm_form(request, object, name=None):
if name is None: if name is None:
name = object name = object
gen_confirm_form(request, _('Do you really want to delete <b>%s</b>?') % name, object.get_absolute_url('delete')) gen_confirm_form(request, _('Do you really want to delete <b>%s</b>?') % name, object.get_absolute_url('delete'))
def render_response(req, *args, **kwargs): def render_response(req, *args, **kwargs):
kwargs['context_instance'] = RequestContext(req) kwargs['context_instance'] = RequestContext(req)
return render_to_response(*args, **kwargs) return render_to_response(*args, **kwargs)
def template(template_name): def template(template_name):
def renderer(func): def renderer(func):
def wrapper(request, *args, **kw): def wrapper(request, *args, **kw):
@ -72,14 +75,17 @@ def permission_required(perm, login_url=None):
return wrapper return wrapper
return renderer return renderer
def render_to_forbitten(request, error=_("Sorry, you have no rights to see this page.")): def render_to_forbitten(request, error=_("Sorry, you have no rights to see this page.")):
return HttpResponseForbidden(render_to_string('403.html', {'error': error}, context_instance=RequestContext(request))) return HttpResponseForbidden(render_to_string('403.html', {'error': error}, context_instance=RequestContext(request)))
def delete_default_permissions(): def delete_default_permissions():
for p in Permission.objects.all(): for p in Permission.objects.all():
if p.codename.startswith('add') or p.codename.startswith('delete') or p.codename.startswith('change'): if p.codename.startswith('add') or p.codename.startswith('delete') or p.codename.startswith('change'):
p.delete() p.delete()
def ajax_request(data): def ajax_request(data):
""" """
generates a HTTPResponse-Object with json-Data for a generates a HTTPResponse-Object with json-Data for a
@ -87,6 +93,7 @@ def ajax_request(data):
""" """
return HttpResponse(json.dumps(data)) return HttpResponse(json.dumps(data))
def _propper_unicode(text): def _propper_unicode(text):
res = '' res = ''
if not isinstance(text, unicode): if not isinstance(text, unicode):