cleanup utils

This commit is contained in:
Oskar Hahn 2012-07-10 13:19:12 +02:00
parent debaa505fb
commit 5fcef8aba4
13 changed files with 245 additions and 210 deletions

View File

@ -15,9 +15,9 @@ from django.utils.translation import ugettext_lazy as _
from mptt.forms import TreeNodeChoiceField
from utils.forms import CssClassMixin
from openslides.utils.forms import CssClassMixin
from agenda.models import Item
from openslides.agenda.models import Item
class ItemForm(forms.ModelForm, CssClassMixin):

View File

@ -11,10 +11,11 @@
"""
from django import forms
from django.utils.translation import ugettext_lazy as _
from utils.forms import CssClassMixin
from models import config
from utils.translation_ext import ugettext_lazy as _
from openslides.utils.forms import CssClassMixin
from openslides.config.models import config
class GeneralConfigForm(forms.Form, CssClassMixin):

View File

@ -15,8 +15,7 @@ from django.contrib.auth.forms import AdminPasswordChangeForm
from django.contrib.auth.models import User, Group, Permission
from django.utils.translation import ugettext_lazy as _, ugettext_noop
from openslides.utils.forms import CssClassMixin
from openslides.utils.translation_ext import LocalizedModelMultipleChoiceField
from openslides.utils.forms import CssClassMixin, LocalizedModelMultipleChoiceField
from openslides.participant.models import Profile
@ -27,6 +26,7 @@ USER_APPLICATION_IMPORT_OPTIONS = [
('DISCARD' , _('Discard applications'))
]
class UserNewForm(forms.ModelForm, CssClassMixin):
first_name = forms.CharField(label=_("First name"))
last_name = forms.CharField(label=_("Last name"))

View File

@ -11,7 +11,8 @@
"""
from django.contrib.auth.models import Permission
from config.models import config
from openslides.config.models import config
class AnonymousAuth(object):
"""
@ -43,7 +44,8 @@ class AnonymousAuth(object):
perms = Permission.objects.filter(group__name='Anonymous')
if perms is None:
return set()
perms = perms.values_list('content_type__app_label', 'codename').order_by()
perms = perms.values_list('content_type__app_label', 'codename') \
.order_by()
return set([u'%s.%s' % (ct, name) for ct, name in perms])
def get_all_permissions(self, user_obj, obj=None):

View File

@ -12,6 +12,7 @@
from csv import Dialect, excel, register_dialect
class excel_semikolon(Dialect):
delimiter = ';'
doublequote = True
@ -20,6 +21,7 @@ class excel_semikolon(Dialect):
quoting = 0
skipinitialspace = False
def patchup(dialect):
if dialect:
if dialect.delimiter in [excel_semikolon.delimiter, excel.delimiter] and \

View File

@ -10,6 +10,28 @@
:license: GNU GPL, see LICENSE for more details.
"""
from django import forms
from django.utils.translation import ugettext_lazy as _
class CssClassMixin(object):
error_css_class = 'error'
required_css_class = 'required'
class LocalizedModelMultipleChoiceField(forms.ModelMultipleChoiceField):
def __init__(self, *args, **kwargs):
self.to_field_name = kwargs.get('to_field_name', None)
super(LocalizedModelMultipleChoiceField, self).__init__(*args, **kwargs)
def _localized_get_choices(self):
if hasattr(self, '_choices'):
return self._choices
c = []
for (id, text) in super(LocalizedModelMultipleChoiceField, self)._get_choices():
text = text.split(' | ')[-1]
c.append((id, _(text)))
return c
choices = property(_localized_get_choices, forms.ChoiceField._set_choices)

View File

@ -11,40 +11,27 @@
"""
from datetime import datetime
import os
from os.path import join as path_join
from django.http import HttpResponse, HttpResponseNotFound
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext as _
from django.utils.translation import ungettext
from django.contrib.auth.models import User
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import cm
from reportlab.lib.styles import ParagraphStyle as PS
from reportlab.lib.styles import StyleSheet1, ParagraphStyle
from reportlab.platypus import SimpleDocTemplate, Paragraph, Frame, PageBreak, Spacer, Table, LongTable, TableStyle, Image
from reportlab.platypus.doctemplate import SimpleDocTemplate
from reportlab.rl_config import defaultPageSize
from reportlab.lib.units import cm
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.rl_config import defaultPageSize
from openslides.agenda.models import Item
from openslides.application.models import Application
from openslides.assignment.models import Assignment
from openslides.participant.models import Profile
from config.models import config
from openslides.settings import SITE_ROOT
from openslides.utils.utils import permission_required
from django.conf import settings
from django.utils.translation import ugettext as _
from openslides.config.models import config
# register new truetype fonts
pdfmetrics.registerFont(TTFont('Ubuntu', os.path.join(SITE_ROOT, 'static/fonts/Ubuntu-R.ttf')))
pdfmetrics.registerFont(TTFont('Ubuntu-Bold', os.path.join(SITE_ROOT, 'static/fonts/Ubuntu-B.ttf')))
pdfmetrics.registerFont(TTFont('Ubuntu-Italic', os.path.join(SITE_ROOT, 'static/fonts/Ubuntu-RI.ttf')))
pdfmetrics.registerFont(TTFont('Ubuntu', path_join(settings.SITE_ROOT,
'static/fonts/Ubuntu-R.ttf')))
pdfmetrics.registerFont(TTFont('Ubuntu-Bold', path_join(settings.SITE_ROOT,
'static/fonts/Ubuntu-B.ttf')))
pdfmetrics.registerFont(TTFont('Ubuntu-Italic', path_join(settings.SITE_ROOT,
'static/fonts/Ubuntu-RI.ttf')))
# set style information
@ -54,58 +41,68 @@ PAGE_WIDTH=defaultPageSize[0]
# set custom stylesheets
stylesheet = StyleSheet1()
stylesheet.add(ParagraphStyle(name = 'Normal',
stylesheet.add(ParagraphStyle(
name='Normal',
fontName='Ubuntu',
fontSize=10,
leading = 12)
)
stylesheet.add(ParagraphStyle(name = 'Paragraph',
leading=12,
))
stylesheet.add(ParagraphStyle(
name='Paragraph',
parent=stylesheet['Normal'],
leading=14,
spaceAfter = 15)
)
stylesheet.add(ParagraphStyle(name = 'Small',
spaceAfter=15
))
stylesheet.add(ParagraphStyle(
name='Small',
parent=stylesheet['Normal'],
fontSize = 8)
)
stylesheet.add(ParagraphStyle(name = 'Italic',
fontSize=8
))
stylesheet.add(ParagraphStyle(
name='Italic',
parent=stylesheet['Normal'],
fontName='Ubuntu-Italic',
spaceAfter = 5)
)
stylesheet.add(ParagraphStyle(name = 'Bold',
spaceAfter=5
))
stylesheet.add(ParagraphStyle(
name='Bold',
parent=stylesheet['Normal'],
fontName = 'Ubuntu-Bold')
)
stylesheet.add(ParagraphStyle(name = 'Heading1',
fontName='Ubuntu-Bold',
))
stylesheet.add(ParagraphStyle(
name='Heading1',
parent=stylesheet['Bold'],
fontSize=24,
leading=30,
spaceAfter = 6),
alias = 'h1')
stylesheet.add(ParagraphStyle(name = 'Heading2',
spaceAfter=6,
), alias='h1')
stylesheet.add(ParagraphStyle(
name='Heading2',
parent=stylesheet['Bold'],
fontSize=14,
leading=24,
spaceAfter = 10),
alias = 'h2')
stylesheet.add(ParagraphStyle(name = 'Heading3',
spaceAfter=10,
), alias='h2')
stylesheet.add(ParagraphStyle(
name='Heading3',
parent=stylesheet['Bold'],
fontSize=12,
leading = 20),
alias = 'h3')
stylesheet.add(ParagraphStyle(name = 'Heading4',
leading=20,
), alias='h3')
stylesheet.add(ParagraphStyle(
name 'Heading4',
parent=stylesheet['Bold'],
fontSize=10,
leading = 20),
)
stylesheet.add(ParagraphStyle(name = 'Item',
leading=20,
))
stylesheet.add(ParagraphStyle(
name='Item',
parent=stylesheet['Normal'],
fontSize=14,
leading=14,
leftIndent=0,
spaceAfter = 15)
)
spaceAfter=15,
))
stylesheet.add(ParagraphStyle(name = 'Subitem',
parent = stylesheet['Normal'],
fontSize = 10,
@ -193,17 +190,19 @@ stylesheet.add(ParagraphStyle(name = 'Badge_subtitle',
leading = 24,
leftIndent = 30),
)
stylesheet.add(ParagraphStyle(name = 'Badge_italic',
stylesheet.add(ParagraphStyle(
name = 'Badge_italic',
parent = stylesheet['Italic'],
fontSize = 12,
leading = 24,
leftIndent = 30),
)
stylesheet.add(ParagraphStyle(name = 'Badge_qrcode',
leftIndent = 30,
))
stylesheet.add(ParagraphStyle(
name = 'Badge_qrcode',
fontSize = 12,
leftIndent = 190),
)
leftIndent = 190,
))
def firstPage(canvas, doc):
canvas.saveState()
@ -211,25 +210,30 @@ def firstPage(canvas, doc):
canvas.setFont('Ubuntu', 10)
canvas.setFillGray(0.4)
title_line = u"%s | %s" % (config["event_name"], config["event_description"])
title_line = u"%s | %s" % (config["event_name"],
config["event_description"])
if len(title_line) > 75:
title_line = "%s ..." % title_line[:70]
canvas.drawString(2.75 * cm, 28 * cm, title_line)
if config["event_date"] and config["event_location"]:
canvas.drawString(2.75 * cm, 27.6 * cm, u"%s, %s" % (config["event_date"], config["event_location"]))
canvas.drawString(2.75 * cm, 27.6 * cm, u"%s, %s"
% (config["event_date"], config["event_location"]))
# time
canvas.setFont('Ubuntu', 7)
time = datetime.now().strftime(str(_("%Y-%m-%d %H:%Mh")))
canvas.drawString(15 * cm, 28 * cm, unicode(_("Printed: %s") % time))
time = datetime.now().strftime(_("%Y-%m-%d %H:%Mh"))
canvas.drawString(15 * cm, 28 * cm, _("Printed: %s") % time)
# title
if doc.title:
canvas.setFont('Ubuntu-Bold', 24)
canvas.setFillGray(0)
canvas.drawString(2.75 * cm, PAGE_HEIGHT - 108, unicode(doc.title))
canvas.drawString(2.75 * cm, PAGE_HEIGHT - 108, doc.title)
# footer (with page number)
canvas.setFont('Ubuntu', 8)
canvas.setFillGray(0.4)
canvas.drawString(10 * cm, 1 * cm, unicode(_("Page %s") % doc.page))
canvas.drawString(10 * cm, 1 * cm, _("Page %s") % doc.page)
canvas.restoreState()
@ -238,5 +242,5 @@ def laterPages(canvas, doc):
# footer (with page number)
canvas.setFont('Ubuntu', 7)
canvas.setFillGray(0.4)
canvas.drawString(10 * cm, 1 * cm, unicode(_("Page %s") % doc.page))
canvas.drawString(10 * cm, 1 * cm, _("Page %s") % doc.page)
canvas.restoreState()

View File

@ -1,3 +1,15 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
openslides.utils.staticfiles
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
StaticFiels fix for the django bug #18404.
:copyright: 2011, 2012 by OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
import os
import sys
@ -7,7 +19,8 @@ from django.contrib.staticfiles.finders import (
AppDirectoriesFinder as _AppDirectoriesFinder)
# This is basically a copy of django.contrib.staticfiles.storage.AppStaticStorage
# This is basically a copy of
# django.contrib.staticfiles.storage.AppStaticStorage
# with the fix for django bug #18404 applied
# see https://code.djangoproject.com/ticket/18404 for details
class AppStaticStorage(FileSystemStorage):
@ -30,5 +43,6 @@ class AppStaticStorage(FileSystemStorage):
location = location.decode(fs_encoding)
super(AppStaticStorage, self).__init__(location, *args, **kwargs)
class AppDirectoriesFinder(_AppDirectoriesFinder):
storage_class = AppStaticStorage

View File

@ -10,9 +10,9 @@
:license: GNU GPL, see LICENSE for more details.
"""
from django.template.loader_tags import BlockNode, ExtendsNode
from django.template import loader, Context, RequestContext, TextNode
from django.http import HttpResponse
from django.template import loader, Context, RequestContext, TextNode
from django.template.loader_tags import BlockNode, ExtendsNode
class Tab(object):
@ -36,7 +36,8 @@ class BlockNotFound(Exception):
def render_template_block(template, block, context):
"""
Renders a single block from a template. This template should have previously been rendered.
Renders a single block from a template. This template should have previously
been rendered.
"""
return render_template_block_nodelist(template.nodelist, block, context)
@ -48,22 +49,25 @@ def render_template_block_nodelist(nodelist, block, context):
for key in ('nodelist', 'nodelist_true', 'nodelist_false'):
if hasattr(node, key):
try:
return render_template_block_nodelist(getattr(node, key), block, context)
return render_template_block_nodelist(getattr(node, key),
block, context)
except:
pass
for node in nodelist:
if isinstance(node, ExtendsNode):
try:
return render_template_block(node.get_parent(context), block, context)
return render_template_block(node.get_parent(context), block,
context)
except BlockNotFound:
pass
raise BlockNotFound
def render_block_to_string(template_name, block, dictionary=None, context_instance=None):
def render_block_to_string(template_name, block, dictionary=None,
context_instance=None):
"""
Loads the given template_name and renders the given block with the given dictionary as
context. Returns a string.
Loads the given template_name and renders the given block with the given
dictionary as context. Returns a string.
"""
dictionary = dictionary or {}
t = get_template(template_name)
@ -75,10 +79,11 @@ def render_block_to_string(template_name, block, dictionary=None, context_instan
return render_template_block(t, block, context_instance)
def direct_block_to_template(request, template, block, extra_context=None, mimetype=None, **kwargs):
def direct_block_to_template(request, template, block, extra_context=None,
mimetype=None, **kwargs):
"""
Render a given block in a given template with any extra URL parameters in the context as
``{{ params }}``.
Render a given block in a given template with any extra URL parameters in
the context as ``{{ params }}``.
"""
if extra_context is None:
extra_context = {}

View File

@ -11,7 +11,7 @@
"""
from django import template
from config.models import config
from openslides.config.models import config
register = template.Library()

View File

@ -1,56 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
openslides.utils.translation_ext
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Localizable descriptions for django permissions.
:copyright: 2011, 2012 by OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
from django.utils.translation import ugettext_lazy
from django.forms import ChoiceField, ModelChoiceField, ModelMultipleChoiceField
class LocalizedModelChoiceField(ModelChoiceField):
def __init__(self, *args, **kwargs):
super(LocalizedModelChoiceField, self).__init__(*args, **kwargs)
def _localized_get_choices(self):
if hasattr(self, '_choices'):
return self._choices
c = []
for (id, text) in super(LocalizedModelMultipleChoiceField, self)._get_choices():
text = text.split(' | ')[-1]
c.append((id, ugettext(text)))
return c
choices = property(_localized_get_choices, ChoiceField._set_choices)
class LocalizedModelMultipleChoiceField(ModelMultipleChoiceField):
def __init__(self, *args, **kwargs):
self.to_field_name = kwargs.get('to_field_name', None)
super(LocalizedModelMultipleChoiceField, self).__init__(*args, **kwargs)
def _localized_get_choices(self):
if hasattr(self, '_choices'):
return self._choices
c = []
for (id, text) in super(LocalizedModelMultipleChoiceField, self)._get_choices():
text = text.split(' | ')[-1]
c.append((id, ugettext(text)))
return c
choices = property(_localized_get_choices, ChoiceField._set_choices)
def ugettext(msg, fixstr=False):
if fixstr:
return msg
else:
return ugettext_lazy(msg)

View File

@ -12,25 +12,23 @@
try:
import json
except ImportError:
except ImportError: # For python 2.5 support
import simplejson as json
from django.shortcuts import render_to_response, redirect
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseForbidden
from django.template import RequestContext
from django.template.loader import render_to_string
from django.core.context_processors import csrf
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.models import Permission
from django.db.models import signals
from django.utils.importlib import import_module
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseForbidden
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.template.loader import render_to_string
from django.utils.translation import ugettext as _
from openslides.utils.signals import template_manipulation
from openslides.utils.translation_ext import ugettext as _
from openslides import get_version
import settings
def revision(request):
@ -38,15 +36,35 @@ def revision(request):
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")))
"""
Generate a message-form.
Deprecated. Use Class base Views instead.
"""
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, delete_link=None):
"""
Creates a question to delete an object.
Deprecated. Use Class base Views instead.
"""
if name is None:
name = object
if delete_link is None:
delete_link = object.get_absolute_url('delete')
gen_confirm_form(request, _('Do you really want to delete <b>%s</b>?') % name, delete_link)
gen_confirm_form(request, _('Do you really want to delete %s?')
% html_strong(name), delete_link)
def render_response(req, *args, **kwargs):
@ -61,9 +79,11 @@ def template(template_name):
if not isinstance(output, dict):
return output
context = {}
template_manipulation.send(sender='utils_template', request=request, context=context)
template_manipulation.send(sender='utils_template', request=request,
context=context)
output.update(context)
response = render_to_response(template_name, output, context_instance=RequestContext(request))
response = render_to_response(template_name, output,
context_instance=RequestContext(request))
if 'cookie' in output:
response.set_cookie(output['cookie'][0], output['cookie'][1])
return response
@ -87,13 +107,20 @@ def permission_required(perm, login_url=None):
return renderer
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)))
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)))
def delete_default_permissions(**kwargs):
"""
Deletes the permissions, django creates by default for the admin.
"""
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()

View File

@ -64,7 +64,8 @@ View = _View
class SetCookieMixin(object):
def render_to_response(self, context, **response_kwargs):
response = TemplateResponseMixin.render_to_response(self, context, **response_kwargs)
response = TemplateResponseMixin.render_to_response(self, context,
**response_kwargs)
if 'cookie' in context:
response.set_cookie(context['cookie'][0], context['cookie'][1])
return response
@ -89,7 +90,8 @@ class PermissionMixin(object):
if not self.has_permission(request):
if not request.user.is_authenticated():
path = request.get_full_path()
return HttpResponseRedirect("%s?next=%s" % (settings.LOGIN_URL, path))
return HttpResponseRedirect("%s?next=%s" % (settings.LOGIN_URL,
path))
else:
return render_to_forbitten(request)
return _View.dispatch(self, request, *args, **kwargs)
@ -106,14 +108,16 @@ class AjaxMixin(object):
class TemplateView(PermissionMixin, _TemplateView):
def get_context_data(self, **kwargs):
context = super(TemplateView, self).get_context_data(**kwargs)
template_manipulation.send(sender=self.__class__, request=self.request, context=context)
template_manipulation.send(sender=self.__class__, request=self.request,
context=context)
return context
class ListView(PermissionMixin, SetCookieMixin, _ListView):
def get_context_data(self, **kwargs):
context = super(ListView, self).get_context_data(**kwargs)
template_manipulation.send(sender=self.__class__, request=self.request, context=context)
template_manipulation.send(sender=self.__class__, request=self.request,
context=context)
return context
@ -154,7 +158,8 @@ class FormView(PermissionMixin, _FormView):
def get_context_data(self, **kwargs):
context = super(FormView, self).get_context_data(**kwargs)
template_manipulation.send(sender=self.__class__, request=self.request, context=context)
template_manipulation.send(sender=self.__class__, request=self.request,
context=context)
return context
def form_invalid(self, form):
@ -171,7 +176,8 @@ class UpdateView(PermissionMixin, _UpdateView):
def get_context_data(self, **kwargs):
context = super(UpdateView, self).get_context_data(**kwargs)
template_manipulation.send(sender=self.__class__, request=self.request, context=context)
template_manipulation.send(sender=self.__class__, request=self.request,
context=context)
return context
def form_invalid(self, form):
@ -191,11 +197,11 @@ class CreateView(PermissionMixin, _CreateView):
def get_context_data(self, **kwargs):
context = super(CreateView, self).get_context_data(**kwargs)
template_manipulation.send(sender=self.__class__, request=self.request, context=context)
template_manipulation.send(sender=self.__class__, request=self.request,
context=context)
return context
def get_apply_url(self):
#todo: Versuche apply url automatisch anhand on self.object herauszufindne
return self.apply_url
def form_invalid(self, form):
@ -225,10 +231,19 @@ class DeleteView(RedirectView, SingleObjectMixin):
return super(DeleteView, self).get(request, *args, **kwargs)
def confirm_form(self, request, object):
self.gen_confirm_form(request, self.get_confirm_question(), object.get_absolute_url('delete'))
self.gen_confirm_form(request, self.get_confirm_question(),
object.get_absolute_url('delete'))
def gen_confirm_form(self, 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")))
class DetailView(TemplateView, SingleObjectMixin):
@ -261,7 +276,8 @@ class PDFView(PermissionMixin, View):
return SimpleDocTemplate(buffer)
def build_document(self, pdf_document, story):
pdf_document.build(story, onFirstPage=firstPage, onLaterPages=laterPages)
pdf_document.build(story, onFirstPage=firstPage,
onLaterPages=laterPages)
def render_to_response(self, filename):
response = HttpResponse(mimetype='application/pdf')
@ -323,12 +339,10 @@ def server_error(request, template_name='500.html'):
500 error handler.
Templates: `500.html`
Context:
MEDIA_URL
Path of static media (e.g. "media.example.org")
"""
t = loader.get_template("500.html") # You need to create a 500.html template.
return HttpResponseServerError(render_to_string('500.html', context_instance=RequestContext(request)))
t = loader.get_template("500.html")
return HttpResponseServerError(render_to_string('500.html',
context_instance=RequestContext(request)))
@receiver(template_manipulation, dispatch_uid="send_register_tab")