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 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): class ItemForm(forms.ModelForm, CssClassMixin):

View File

@ -11,10 +11,11 @@
""" """
from django import forms from django import forms
from django.utils.translation import ugettext_lazy as _
from utils.forms import CssClassMixin from openslides.utils.forms import CssClassMixin
from models import config
from utils.translation_ext import ugettext_lazy as _ from openslides.config.models import config
class GeneralConfigForm(forms.Form, CssClassMixin): 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.contrib.auth.models import User, Group, Permission
from django.utils.translation import ugettext_lazy as _, ugettext_noop from django.utils.translation import ugettext_lazy as _, ugettext_noop
from openslides.utils.forms import CssClassMixin from openslides.utils.forms import CssClassMixin, LocalizedModelMultipleChoiceField
from openslides.utils.translation_ext import LocalizedModelMultipleChoiceField
from openslides.participant.models import Profile from openslides.participant.models import Profile
@ -27,6 +26,7 @@ USER_APPLICATION_IMPORT_OPTIONS = [
('DISCARD' , _('Discard applications')) ('DISCARD' , _('Discard applications'))
] ]
class UserNewForm(forms.ModelForm, CssClassMixin): class UserNewForm(forms.ModelForm, CssClassMixin):
first_name = forms.CharField(label=_("First name")) first_name = forms.CharField(label=_("First name"))
last_name = forms.CharField(label=_("Last name")) last_name = forms.CharField(label=_("Last name"))

View File

@ -11,7 +11,8 @@
""" """
from django.contrib.auth.models import Permission from django.contrib.auth.models import Permission
from config.models import config from openslides.config.models import config
class AnonymousAuth(object): class AnonymousAuth(object):
""" """
@ -43,7 +44,8 @@ class AnonymousAuth(object):
perms = Permission.objects.filter(group__name='Anonymous') perms = Permission.objects.filter(group__name='Anonymous')
if perms is None: if perms is None:
return set() 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]) return set([u'%s.%s' % (ct, name) for ct, name in perms])
def get_all_permissions(self, user_obj, obj=None): def get_all_permissions(self, user_obj, obj=None):
@ -90,5 +92,5 @@ def anonymous_context_additions(RequestContext):
Add a variable to the request context that will indicate Add a variable to the request context that will indicate
if anonymous login is possible at all. if anonymous login is possible at all.
""" """
return { 'os_enable_anonymous_login' : config['system_enable_anonymous']} return {'os_enable_anonymous_login' : config['system_enable_anonymous']}

View File

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

View File

@ -10,6 +10,28 @@
:license: GNU GPL, see LICENSE for more details. :license: GNU GPL, see LICENSE for more details.
""" """
from django import forms
from django.utils.translation import ugettext_lazy as _
class CssClassMixin(object): class CssClassMixin(object):
error_css_class = 'error' error_css_class = 'error'
required_css_class = 'required' 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,101 +11,98 @@
""" """
from datetime import datetime 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.lib.styles import StyleSheet1, ParagraphStyle
from reportlab.platypus import SimpleDocTemplate, Paragraph, Frame, PageBreak, Spacer, Table, LongTable, TableStyle, Image from reportlab.lib.units import cm
from reportlab.platypus.doctemplate import SimpleDocTemplate
from reportlab.rl_config import defaultPageSize
from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfbase.ttfonts import TTFont
from reportlab.rl_config import defaultPageSize
from openslides.agenda.models import Item from django.conf import settings
from openslides.application.models import Application from django.utils.translation import ugettext as _
from openslides.assignment.models import Assignment
from openslides.participant.models import Profile from openslides.config.models import config
from config.models import config
from openslides.settings import SITE_ROOT
from openslides.utils.utils import permission_required
# register new truetype fonts # register new truetype fonts
pdfmetrics.registerFont(TTFont('Ubuntu', os.path.join(SITE_ROOT, 'static/fonts/Ubuntu-R.ttf'))) pdfmetrics.registerFont(TTFont('Ubuntu', path_join(settings.SITE_ROOT,
pdfmetrics.registerFont(TTFont('Ubuntu-Bold', os.path.join(SITE_ROOT, 'static/fonts/Ubuntu-B.ttf'))) 'static/fonts/Ubuntu-R.ttf')))
pdfmetrics.registerFont(TTFont('Ubuntu-Italic', os.path.join(SITE_ROOT, 'static/fonts/Ubuntu-RI.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 # set style information
PAGE_HEIGHT=defaultPageSize[1]; PAGE_HEIGHT = defaultPageSize[1];
PAGE_WIDTH=defaultPageSize[0] PAGE_WIDTH = defaultPageSize[0]
# set custom stylesheets # set custom stylesheets
stylesheet = StyleSheet1() stylesheet = StyleSheet1()
stylesheet.add(ParagraphStyle(name = 'Normal', stylesheet.add(ParagraphStyle(
fontName = 'Ubuntu', name='Normal',
fontSize = 10, fontName='Ubuntu',
leading = 12) fontSize=10,
) leading=12,
stylesheet.add(ParagraphStyle(name = 'Paragraph', ))
parent = stylesheet['Normal'], stylesheet.add(ParagraphStyle(
leading = 14, name='Paragraph',
spaceAfter = 15) parent=stylesheet['Normal'],
) leading=14,
stylesheet.add(ParagraphStyle(name = 'Small', spaceAfter=15
parent = stylesheet['Normal'], ))
fontSize = 8) stylesheet.add(ParagraphStyle(
) name='Small',
stylesheet.add(ParagraphStyle(name = 'Italic', parent=stylesheet['Normal'],
parent = stylesheet['Normal'], fontSize=8
fontName = 'Ubuntu-Italic', ))
spaceAfter = 5) stylesheet.add(ParagraphStyle(
) name='Italic',
stylesheet.add(ParagraphStyle(name = 'Bold', parent=stylesheet['Normal'],
parent = stylesheet['Normal'], fontName='Ubuntu-Italic',
fontName = 'Ubuntu-Bold') spaceAfter=5
) ))
stylesheet.add(ParagraphStyle(name = 'Heading1', stylesheet.add(ParagraphStyle(
parent = stylesheet['Bold'], name='Bold',
fontSize = 24, parent=stylesheet['Normal'],
leading = 30, fontName='Ubuntu-Bold',
spaceAfter = 6), ))
alias = 'h1') stylesheet.add(ParagraphStyle(
stylesheet.add(ParagraphStyle(name = 'Heading2', name='Heading1',
parent = stylesheet['Bold'], parent=stylesheet['Bold'],
fontSize = 14, fontSize=24,
leading = 24, leading=30,
spaceAfter = 10), spaceAfter=6,
alias = 'h2') ), alias='h1')
stylesheet.add(ParagraphStyle(name = 'Heading3', stylesheet.add(ParagraphStyle(
parent = stylesheet['Bold'], name='Heading2',
fontSize = 12, parent=stylesheet['Bold'],
leading = 20), fontSize=14,
alias = 'h3') leading=24,
stylesheet.add(ParagraphStyle(name = 'Heading4', spaceAfter=10,
parent = stylesheet['Bold'], ), alias='h2')
fontSize = 10, stylesheet.add(ParagraphStyle(
leading = 20), name='Heading3',
) parent=stylesheet['Bold'],
stylesheet.add(ParagraphStyle(name = 'Item', fontSize=12,
parent = stylesheet['Normal'], leading=20,
fontSize = 14, ), alias='h3')
leading = 14, stylesheet.add(ParagraphStyle(
leftIndent = 0, name 'Heading4',
spaceAfter = 15) parent=stylesheet['Bold'],
) fontSize=10,
leading=20,
))
stylesheet.add(ParagraphStyle(
name='Item',
parent=stylesheet['Normal'],
fontSize=14,
leading=14,
leftIndent=0,
spaceAfter=15,
))
stylesheet.add(ParagraphStyle(name = 'Subitem', stylesheet.add(ParagraphStyle(name = 'Subitem',
parent = stylesheet['Normal'], parent = stylesheet['Normal'],
fontSize = 10, fontSize = 10,
@ -193,17 +190,19 @@ stylesheet.add(ParagraphStyle(name = 'Badge_subtitle',
leading = 24, leading = 24,
leftIndent = 30), leftIndent = 30),
) )
stylesheet.add(ParagraphStyle(name = 'Badge_italic', stylesheet.add(ParagraphStyle(
parent = stylesheet['Italic'], name = 'Badge_italic',
fontSize = 12, parent = stylesheet['Italic'],
leading = 24, fontSize = 12,
leftIndent = 30), leading = 24,
) leftIndent = 30,
))
stylesheet.add(ParagraphStyle(
name = 'Badge_qrcode',
fontSize = 12,
leftIndent = 190,
))
stylesheet.add(ParagraphStyle(name = 'Badge_qrcode',
fontSize = 12,
leftIndent = 190),
)
def firstPage(canvas, doc): def firstPage(canvas, doc):
canvas.saveState() canvas.saveState()
@ -211,25 +210,30 @@ def firstPage(canvas, doc):
canvas.setFont('Ubuntu', 10) canvas.setFont('Ubuntu', 10)
canvas.setFillGray(0.4) 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: if len(title_line) > 75:
title_line = "%s ..." % title_line[:70] title_line = "%s ..." % title_line[:70]
canvas.drawString(2.75 * cm, 28 * cm, title_line) canvas.drawString(2.75 * cm, 28 * cm, title_line)
if config["event_date"] and config["event_location"]: 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 # time
canvas.setFont('Ubuntu', 7) canvas.setFont('Ubuntu', 7)
time = datetime.now().strftime(str(_("%Y-%m-%d %H:%Mh"))) time = datetime.now().strftime(_("%Y-%m-%d %H:%Mh"))
canvas.drawString(15 * cm, 28 * cm, unicode(_("Printed: %s") % time)) canvas.drawString(15 * cm, 28 * cm, _("Printed: %s") % time)
# title # title
if doc.title: if doc.title:
canvas.setFont('Ubuntu-Bold', 24) canvas.setFont('Ubuntu-Bold', 24)
canvas.setFillGray(0) 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) # footer (with page number)
canvas.setFont('Ubuntu', 8) canvas.setFont('Ubuntu', 8)
canvas.setFillGray(0.4) 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() canvas.restoreState()
@ -238,5 +242,5 @@ def laterPages(canvas, doc):
# footer (with page number) # footer (with page number)
canvas.setFont('Ubuntu', 7) canvas.setFont('Ubuntu', 7)
canvas.setFillGray(0.4) 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() 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 os
import sys import sys
@ -7,7 +19,8 @@ from django.contrib.staticfiles.finders import (
AppDirectoriesFinder as _AppDirectoriesFinder) 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 # with the fix for django bug #18404 applied
# see https://code.djangoproject.com/ticket/18404 for details # see https://code.djangoproject.com/ticket/18404 for details
class AppStaticStorage(FileSystemStorage): class AppStaticStorage(FileSystemStorage):
@ -30,5 +43,6 @@ class AppStaticStorage(FileSystemStorage):
location = location.decode(fs_encoding) location = location.decode(fs_encoding)
super(AppStaticStorage, self).__init__(location, *args, **kwargs) super(AppStaticStorage, self).__init__(location, *args, **kwargs)
class AppDirectoriesFinder(_AppDirectoriesFinder): class AppDirectoriesFinder(_AppDirectoriesFinder):
storage_class = AppStaticStorage storage_class = AppStaticStorage

View File

@ -10,9 +10,9 @@
:license: GNU GPL, see LICENSE for more details. :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.http import HttpResponse
from django.template import loader, Context, RequestContext, TextNode
from django.template.loader_tags import BlockNode, ExtendsNode
class Tab(object): class Tab(object):
@ -36,7 +36,8 @@ class BlockNotFound(Exception):
def render_template_block(template, block, context): 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) 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'): for key in ('nodelist', 'nodelist_true', 'nodelist_false'):
if hasattr(node, key): if hasattr(node, key):
try: try:
return render_template_block_nodelist(getattr(node, key), block, context) return render_template_block_nodelist(getattr(node, key),
block, context)
except: except:
pass pass
for node in nodelist: for node in nodelist:
if isinstance(node, ExtendsNode): if isinstance(node, ExtendsNode):
try: try:
return render_template_block(node.get_parent(context), block, context) return render_template_block(node.get_parent(context), block,
context)
except BlockNotFound: except BlockNotFound:
pass pass
raise BlockNotFound 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 Loads the given template_name and renders the given block with the given
context. Returns a string. dictionary as context. Returns a string.
""" """
dictionary = dictionary or {} dictionary = dictionary or {}
t = get_template(template_name) 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) 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 Render a given block in a given template with any extra URL parameters in
``{{ params }}``. the context as ``{{ params }}``.
""" """
if extra_context is None: if extra_context is None:
extra_context = {} extra_context = {}

View File

@ -11,7 +11,7 @@
""" """
from django import template from django import template
from config.models import config from openslides.config.models import config
register = template.Library() 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: try:
import json import json
except ImportError: except ImportError: # For python 2.5 support
import simplejson as json import simplejson as json
from django.shortcuts import render_to_response, redirect from django.conf import settings
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.contrib import messages from django.contrib import messages
from django.contrib.auth.models import Permission from django.contrib.auth.models import Permission
from django.db.models import signals from django.core.context_processors import csrf
from django.utils.importlib import import_module 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.signals import template_manipulation
from openslides.utils.translation_ext import ugettext as _
from openslides import get_version from openslides import get_version
import settings
def revision(request): def revision(request):
@ -38,15 +36,35 @@ 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"))) """
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): 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: if name is None:
name = object name = object
if delete_link is None: if delete_link is None:
delete_link = object.get_absolute_url('delete') 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): def render_response(req, *args, **kwargs):
@ -61,9 +79,11 @@ def template(template_name):
if not isinstance(output, dict): if not isinstance(output, dict):
return output return output
context = {} context = {}
template_manipulation.send(sender='utils_template', request=request, context=context) template_manipulation.send(sender='utils_template', request=request,
context=context)
output.update(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: if 'cookie' in output:
response.set_cookie(output['cookie'][0], output['cookie'][1]) response.set_cookie(output['cookie'][0], output['cookie'][1])
return response return response
@ -87,13 +107,20 @@ def permission_required(perm, login_url=None):
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=
return HttpResponseForbidden(render_to_string('403.html', {'error': error}, context_instance=RequestContext(request))) _("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): def delete_default_permissions(**kwargs):
"""
Deletes the permissions, django creates by default for the admin.
"""
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()

View File

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