{{ group.name }} |
- {% if group.name|lower != 'anonymous' %}
+ {% if group.name|lower != 'anonymous' and group.name|lower != 'registered' %}
{% endif %}
|
diff --git a/openslides/participant/urls.py b/openslides/participant/urls.py
index e3ac2e553..569f8b85f 100644
--- a/openslides/participant/urls.py
+++ b/openslides/participant/urls.py
@@ -11,7 +11,6 @@
"""
from django.conf.urls.defaults import url, patterns
-from django.core.urlresolvers import reverse
from openslides.participant.views import (
UserOverview, UserCreateView, UserDetailView, UserUpdateView,
diff --git a/openslides/participant/views.py b/openslides/participant/views.py
index b4be8b998..c0fa8d6c5 100644
--- a/openslides/participant/views.py
+++ b/openslides/participant/views.py
@@ -28,7 +28,6 @@ from reportlab.platypus import (
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import PasswordChangeForm
-from django.contrib.auth.models import User
from django.contrib.auth.views import login as django_login
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
@@ -39,16 +38,12 @@ from openslides.utils.template import Tab
from openslides.utils.utils import (
template, decodedict, encodedict, delete_default_permissions, html_strong)
from openslides.utils.views import (
- FormView, PDFView, CreateView, UpdateView, DeleteView,
- RedirectView, SingleObjectMixin, ListView, QuestionMixin)
-
+ FormView, PDFView, CreateView, UpdateView, DeleteView, PermissionMixin,
+ RedirectView, SingleObjectMixin, ListView, QuestionMixin, DetailView)
from openslides.config.models import config
-
from openslides.projector.projector import Widget
-
from openslides.motion.models import Motion
from openslides.assignment.models import Assignment
-
from openslides.participant.api import gen_username, gen_password, import_users
from openslides.participant.forms import (
UserCreateForm, UserUpdateForm, UsersettingsForm,
@@ -125,11 +120,13 @@ class UserOverview(ListView):
percent = 0
# list of all existing categories
- structure_levels = [p['structure_level'] for p in User.objects.values('structure_level')
- .exclude(structure_level='').distinct()]
+ structure_levels = [
+ p['structure_level'] for p in
+ User.objects.values('structure_level').exclude(structure_level='').distinct()]
# list of all existing committees
- committees = [p['committee'] for p in User.objects.values('committee')
- .exclude(committee='').distinct()]
+ committees = [
+ p['committee'] for p in
+ User.objects.values('committee').exclude(committee='').distinct()]
# context vars
context.update({
'allusers': all_users,
@@ -137,13 +134,13 @@ class UserOverview(ListView):
'percent': round(percent, 1),
'structure_levels': structure_levels,
'committees': committees,
- 'cookie': ['participant_sortfilter', urlencode(decodedict(self.sortfilter),
+ 'cookie': [
+ 'participant_sortfilter', urlencode(decodedict(self.sortfilter),
doseq=True)],
'sortfilter': self.sortfilter})
return context
-from openslides.utils.views import DetailView, PermissionMixin
class UserDetailView(DetailView, PermissionMixin):
"""
Classed based view to show a specific user in the interface.
@@ -177,8 +174,8 @@ class UserCreateView(CreateView):
apply_url = 'user_edit'
def manipulate_object(self, form):
- self.object.username = gen_username(form.cleaned_data['first_name'],
- form.cleaned_data['last_name'])
+ self.object.username = gen_username(
+ form.cleaned_data['first_name'], form.cleaned_data['last_name'])
if not self.object.default_password:
self.object.default_password = gen_password()
self.object.set_password(self.object.default_password)
@@ -211,6 +208,7 @@ class UserDeleteView(DeleteView):
else:
super(UserDeleteView, self).pre_redirect(request, *args, **kwargs)
+
class SetUserStatusView(RedirectView, SingleObjectMixin):
"""
Activate or deactivate an user.
@@ -547,8 +545,9 @@ def register_tab(request):
return Tab(
title=_('Participants'),
url=reverse('user_overview'),
- permission=request.user.has_perm('participant.can_see_participant') or
- request.user.has_perm('participant.can_manage_participant'),
+ permission=(
+ request.user.has_perm('participant.can_see_participant') or
+ request.user.has_perm('participant.can_manage_participant')),
selected=selected)
@@ -569,12 +568,12 @@ def get_personal_info_widget(request):
and where you are supporter or candidate.
"""
personal_info_context = {
- 'submitted_motions': Motion.objects.filter(submitter=request.user),
- 'config_motion_min_supporters': config['motion_min_supporters'],
- 'supported_motions': Motion.objects.filter(motionsupporter=request.user),
- 'assignments': Assignment.objects.filter(
- assignmentcandidate__person=request.user,
- assignmentcandidate__blocked=False),}
+ 'submitted_motions': Motion.objects.filter(submitter=request.user),
+ 'config_motion_min_supporters': config['motion_min_supporters'],
+ 'supported_motions': Motion.objects.filter(motionsupporter=request.user),
+ 'assignments': Assignment.objects.filter(
+ assignmentcandidate__person=request.user,
+ assignmentcandidate__blocked=False)}
return Widget(
name='personal_info',
display_name=_('My motions and elections'),
@@ -593,7 +592,7 @@ def get_user_widget(request):
name='user',
display_name=_('Participants'),
template='participant/user_widget.html',
- context={'users': User.objects.all(),},
+ context={'users': User.objects.all()},
permission_required='projector.can_manage_projector',
default_column=1)
@@ -607,6 +606,6 @@ def get_group_widget(request):
name='group',
display_name=_('Groups'),
template='participant/group_widget.html',
- context={'groups': Group.objects.all(),},
+ context={'groups': Group.objects.all()},
permission_required='projector.can_manage_projector',
default_column=1)
diff --git a/openslides/poll/forms.py b/openslides/poll/forms.py
index 2fd893b11..7d4db9822 100644
--- a/openslides/poll/forms.py
+++ b/openslides/poll/forms.py
@@ -11,7 +11,6 @@
"""
from django import forms
-from django.utils.translation import ugettext_lazy as _
from openslides.utils.forms import CssClassMixin
diff --git a/openslides/poll/models.py b/openslides/poll/models.py
index a38514619..19821b3d1 100644
--- a/openslides/poll/models.py
+++ b/openslides/poll/models.py
@@ -47,7 +47,7 @@ class BaseVote(models.Model):
Subclasses have to define a option-field, which are a subclass of
BaseOption.
"""
- weight = models.IntegerField(default=1, null=True) # Use MinMaxIntegerField
+ weight = models.IntegerField(default=1, null=True) # Use MinMaxIntegerField
value = models.CharField(max_length=255, null=True)
def print_weight(self, raw=False):
@@ -73,7 +73,7 @@ class BaseVote(models.Model):
class CountVotesCast(models.Model):
votescast = MinMaxIntegerField(null=True, blank=True, min_value=-2,
- verbose_name=_("Votes cast"))
+ verbose_name=_("Votes cast"))
def append_pollform_fields(self, fields):
fields.append('votescast')
@@ -92,7 +92,7 @@ class CountVotesCast(models.Model):
class CountInvalid(models.Model):
votesinvalid = MinMaxIntegerField(null=True, blank=True, min_value=-2,
- verbose_name=_("Votes invalid"))
+ verbose_name=_("Votes invalid"))
def append_pollform_fields(self, fields):
fields.append('votesinvalid')
@@ -164,7 +164,6 @@ class BasePoll(models.Model):
"""
return self.vote_values
-
def get_vote_class(self):
"""
Return the releatet vote class.
@@ -212,7 +211,7 @@ class BasePoll(models.Model):
"""
from openslides.poll.forms import OptionForm
return OptionForm(extra=self.get_form_values(kwargs['formid']),
- **kwargs)
+ **kwargs)
def get_vote_forms(self, **kwargs):
"""
diff --git a/openslides/poll/views.py b/openslides/poll/views.py
index ef58218d9..70c48e7cc 100644
--- a/openslides/poll/views.py
+++ b/openslides/poll/views.py
@@ -35,7 +35,7 @@ class PollFormView(TemplateView):
context['forms'] = self.poll.get_vote_forms()
FormClass = self.get_modelform_class()
context['pollform'] = FormClass(instance=self.poll,
- prefix='pollform')
+ prefix='pollform')
return context
def get_success_url(self):
@@ -52,7 +52,7 @@ class PollFormView(TemplateView):
FormClass = self.get_modelform_class()
pollform = FormClass(data=self.request.POST, instance=self.poll,
- prefix='pollform')
+ prefix='pollform')
error = False
for form in option_forms:
diff --git a/openslides/projector/api.py b/openslides/projector/api.py
index 6bcc04772..7cbd5da02 100644
--- a/openslides/projector/api.py
+++ b/openslides/projector/api.py
@@ -12,12 +12,11 @@
from django.conf import settings
from django.core.cache import cache
-from django.template.loader import render_to_string
from django.utils.datastructures import SortedDict
from django.utils.importlib import import_module
from openslides.config.models import config
-from openslides.projector.projector import SLIDE, Slide, Widget
+from openslides.projector.projector import SLIDE, Slide
def split_sid(sid):
@@ -95,27 +94,18 @@ def clear_projector_cache():
cache.delete('projector_data')
-def register_slidemodel(model, model_name=None, control_template=None,
- weight=0):
+def register_slidemodel(model, model_name=None, control_template=None, weight=0):
"""
Register a Model as a slide.
"""
+ # TODO: control_template should never be None
if model_name is None:
model_name = model.prefix
- if control_template is None:
- control_template = 'projector/default_control_slidemodel.html'
-
category = model.__module__.split('.')[0]
- SLIDE[model_name] = Slide(
- model_slide=True,
- model=model,
- category=category,
- key=model.prefix,
- model_name=model_name,
- control_template=control_template,
- weight=weight,
- )
+ SLIDE[model_name] = Slide(model_slide=True, model=model, category=category,
+ key=model.prefix, model_name=model_name,
+ control_template=control_template, weight=weight)
def register_slidefunc(key, func, control_template=None, weight=0, name=''):
@@ -125,15 +115,9 @@ def register_slidefunc(key, func, control_template=None, weight=0, name=''):
if control_template is None:
control_template = 'projector/default_control_slidefunc.html'
category = func.__module__.split('.')[0]
- SLIDE[key] = Slide(
- model_slide=False,
- func=func,
- category=category,
- key=key,
- control_template=control_template,
- weight=weight,
- name=name,
- )
+ SLIDE[key] = Slide(model_slide=False, func=func, category=category,
+ key=key, control_template=control_template, weight=weight,
+ name=name,)
def projector_message_set(message, sid=None):
@@ -147,7 +131,7 @@ def projector_message_set(message, sid=None):
overlay = ProjectorOverlay.objects.get(def_name='Message')
except ProjectorOverlay.DoesNotExist:
overlay = ProjectorOverlay(def_name='Message', active=False)
- overlay.sid=sid
+ overlay.sid = sid
overlay.save()
@@ -166,7 +150,6 @@ def get_all_widgets(request, session=False):
mod = import_module(app + '.views')
except ImportError:
continue
- appname = mod.__name__.split('.')[0]
try:
modul_widgets = mod.get_widgets(request)
except AttributeError:
diff --git a/openslides/projector/forms.py b/openslides/projector/forms.py
index 3c8d24498..59d69ef9c 100644
--- a/openslides/projector/forms.py
+++ b/openslides/projector/forms.py
@@ -11,7 +11,6 @@
"""
from django import forms
-from django.utils.translation import ugettext_lazy as _
from openslides.utils.forms import CssClassMixin
diff --git a/openslides/projector/models.py b/openslides/projector/models.py
index 299b41afb..f403b6395 100644
--- a/openslides/projector/models.py
+++ b/openslides/projector/models.py
@@ -19,9 +19,6 @@ from openslides.config.signals import default_config_value
from openslides.projector.api import register_slidemodel
from openslides.projector.projector import SlideMixin
-from openslides.config.models import config
-
-
class ProjectorSlide(models.Model, SlideMixin):
"""
@@ -56,8 +53,7 @@ class ProjectorSlide(models.Model, SlideMixin):
)
-register_slidemodel(ProjectorSlide,
- control_template='projector/control_customslide.html')
+register_slidemodel(ProjectorSlide, control_template='projector/control_customslide.html')
class ProjectorOverlay(models.Model):
diff --git a/openslides/projector/projector.py b/openslides/projector/projector.py
index a35e0517b..6e3129f4b 100644
--- a/openslides/projector/projector.py
+++ b/openslides/projector/projector.py
@@ -19,9 +19,9 @@ from openslides.config.models import config
from openslides.projector.signals import projector_overlays
-
SLIDE = {}
+
class SlideMixin(object):
"""
A Mixin for a Django-Model, for making the model a slide.
@@ -49,13 +49,16 @@ class SlideMixin(object):
"""
Return True, if the the slide is the active slide.
"""
- from api import get_active_slide
+ if self.id is None:
+ return False
+ from openslides.projector.api import get_active_slide
return get_active_slide(only_sid=True) == self.sid
def set_active(self):
"""
Appoint this item as the active slide.
"""
+ from openslides.projector.api import set_active_slide
set_active_slide(self.sid)
def save(self, *args, **kwargs):
@@ -112,7 +115,7 @@ class Widget(object):
Class for a Widget for the Projector-Tab.
"""
def __init__(self, name, html=None, template=None, context={},
- permission_required=None, display_name=None, default_column=1):
+ permission_required=None, display_name=None, default_column=1):
self.name = name
if display_name is None:
self.display_name = name.capitalize()
diff --git a/openslides/projector/views.py b/openslides/projector/views.py
index e9ab1b3ec..997e89cf2 100644
--- a/openslides/projector/views.py
+++ b/openslides/projector/views.py
@@ -13,34 +13,28 @@
from datetime import datetime
from time import time
-from django.conf import settings
from django.contrib import messages
from django.core.cache import cache
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.db import transaction
from django.db.models import Q
-from django.dispatch import receiver
from django.shortcuts import redirect
from django.template import RequestContext
-from django.utils.datastructures import SortedDict
-from django.utils.importlib import import_module
from django.utils.translation import ugettext_lazy as _
from openslides.utils.template import render_block_to_string, Tab
-from openslides.utils.utils import html_strong
-from openslides.utils.views import (TemplateView, RedirectView, CreateView,
- UpdateView, DeleteView, AjaxMixin)
-
+from openslides.utils.views import (
+ TemplateView, RedirectView, CreateView, UpdateView, DeleteView, AjaxMixin)
from openslides.config.models import config
-
-from openslides.projector.api import (get_active_slide, set_active_slide,
- projector_message_set, projector_message_delete, get_slide_from_sid,
- get_all_widgets, clear_projector_cache)
-from openslides.projector.forms import SelectWidgetsForm
-from openslides.projector.models import ProjectorOverlay, ProjectorSlide
-from openslides.projector.projector import SLIDE, Widget
-from openslides.projector.signals import projector_overlays
+from .api import (
+ get_active_slide, set_active_slide, projector_message_set,
+ projector_message_delete, get_slide_from_sid, get_all_widgets,
+ clear_projector_cache)
+from .forms import SelectWidgetsForm
+from .models import ProjectorOverlay, ProjectorSlide
+from .projector import Widget
+from .signals import projector_overlays
class DashboardView(TemplateView, AjaxMixin):
@@ -73,7 +67,7 @@ class Projector(TemplateView, AjaxMixin):
if sid is None:
try:
data = get_active_slide()
- except AttributeError: #TODO: It has to be an Slide.DoesNotExist
+ except AttributeError: # TODO: It has to be an Slide.DoesNotExist
data = None
ajax = 'on'
active_sid = get_active_slide(True)
@@ -92,10 +86,10 @@ class Projector(TemplateView, AjaxMixin):
# Projector Overlays
if self.kwargs['sid'] is None:
active_defs = ProjectorOverlay.objects.filter(active=True) \
- .filter(Q(sid=active_sid) | Q(sid=None)).values_list('def_name',
- flat=True)
- for receiver, response in projector_overlays.send(sender=sid,
- register=False, call=active_defs):
+ .filter(Q(sid=active_sid) | Q(sid=None)).values_list(
+ 'def_name', flat=True)
+ for receiver, response in projector_overlays.send(
+ sender=sid, register=False, call=active_defs):
if response is not None:
data['overlays'].append(response)
self._data = data
@@ -124,7 +118,6 @@ class Projector(TemplateView, AjaxMixin):
'scrollcontent', self.data)
cache.set('projector_scrollcontent', scrollcontent, 1)
-
# TODO: do not call the hole data-methode, if we only need some vars
data = cache.get('projector_data')
if not data:
@@ -301,7 +294,6 @@ class OverlayMessageView(RedirectView):
elif 'message-clean' in request.POST:
projector_message_delete()
-
def get_ajax_context(self, **kwargs):
clear_projector_cache()
return {
@@ -309,7 +301,6 @@ class OverlayMessageView(RedirectView):
}
-
class ActivateOverlay(RedirectView):
"""
Activate or deactivate an overlay.
@@ -379,12 +370,11 @@ def register_tab(request):
"""
Register the projector tab.
"""
- selected = True if request.path.startswith('/projector/') else False
+ selected = request.path.startswith('/projector/')
return Tab(
title=_('Dashboard'),
url=reverse('dashboard'),
- permission=request.user.has_perm('projector.can_manage_projector') or
- request.user.has_perm('projector.can_see_dashboard'),
+ permission=request.user.has_perm('projector.can_see_dashboard'),
selected=selected,
)
@@ -411,7 +401,7 @@ def get_widgets(request):
name='live_view',
display_name=_('Projector live view'),
template='projector/live_view_widget.html',
- context = RequestContext(request, {}),
+ context=RequestContext(request, {}),
permission_required='projector.can_see_projector',
default_column=2))
@@ -424,15 +414,14 @@ def get_widgets(request):
projector_overlay = ProjectorOverlay.objects.get(
def_name=name)
except ProjectorOverlay.DoesNotExist:
- projector_overlay = ProjectorOverlay(def_name=name,
- active=False)
+ projector_overlay = ProjectorOverlay(def_name=name, active=False)
projector_overlay.save()
overlays.append(projector_overlay)
context = {
- 'overlays':overlays,
- 'countdown_time': config['countdown_time'],
- 'countdown_state' : config['countdown_state']}
+ 'overlays': overlays,
+ 'countdown_time': config['countdown_time'],
+ 'countdown_state': config['countdown_state']}
context.update(csrf(request))
widgets.append(Widget(
name='overlays',
@@ -442,7 +431,6 @@ def get_widgets(request):
default_column=2,
context=context))
-
# Custom slide widget
context = {
'slides': ProjectorSlide.objects.all().order_by('weight'),
diff --git a/openslides/urls.py b/openslides/urls.py
index 509fea41c..5edb948d0 100644
--- a/openslides/urls.py
+++ b/openslides/urls.py
@@ -12,8 +12,6 @@
from django.conf import settings
from django.conf.urls.defaults import patterns, url, include
-from django.contrib.staticfiles.urls import staticfiles_urlpatterns
-from django.shortcuts import redirect
from django.utils.importlib import import_module
from openslides.utils.views import RedirectView
@@ -34,7 +32,7 @@ urlpatterns = patterns('',
)
urlpatterns += patterns('django.contrib.staticfiles.views',
- url(r'^static/(?P.*)$', 'serve', {'insecure':True}),
+ url(r'^static/(?P.*)$', 'serve', {'insecure': True}),
)
js_info_dict = {
diff --git a/openslides/utils/auth/AnonymousAuth.py b/openslides/utils/auth/AnonymousAuth.py
index 8d21cc1e0..e6c4b27fe 100644
--- a/openslides/utils/auth/AnonymousAuth.py
+++ b/openslides/utils/auth/AnonymousAuth.py
@@ -37,8 +37,8 @@ class AnonymousAuth(object):
- try to return the permissions for the 'Anonymous' group
"""
- if not user_obj.is_anonymous() or obj is not None or \
- not config['system_enable_anonymous']:
+ if (not user_obj.is_anonymous() or obj is not None or
+ not config['system_enable_anonymous']):
return set()
perms = Permission.objects.filter(group__name='Anonymous')
@@ -60,8 +60,8 @@ class AnonymousAuth(object):
"""
Check if the user as a specific permission
"""
- if not user_obj.is_anonymous() or obj is not None or \
- not config['system_enable_anonymous']:
+ if (not user_obj.is_anonymous() or obj is not None or
+ not config['system_enable_anonymous']):
return False
return (perm in self.get_all_permissions(user_obj))
@@ -70,8 +70,8 @@ class AnonymousAuth(object):
"""
Check if the user has permissions on the module app_label
"""
- if not user_obj.is_anonymous() or \
- not config['system_enable_anonymous']:
+ if (not user_obj.is_anonymous() or
+ not config['system_enable_anonymous']):
return False
for perm in self.get_all_permissions(user_obj):
@@ -87,10 +87,10 @@ class AnonymousAuth(object):
"""
return None
+
def anonymous_context_additions(RequestContext):
"""
Add a variable to the request context that will indicate
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']}
diff --git a/openslides/utils/csv_ext.py b/openslides/utils/csv_ext.py
index 864de5cf4..4f2fa8c4a 100644
--- a/openslides/utils/csv_ext.py
+++ b/openslides/utils/csv_ext.py
@@ -25,10 +25,9 @@ class excel_semikolon(Dialect):
def patchup(dialect):
if dialect:
if dialect.delimiter in [excel_semikolon.delimiter, excel.delimiter] and \
- dialect.quotechar == excel_semikolon.quotechar:
+ dialect.quotechar == excel_semikolon.quotechar:
# walks like a duck and talks like a duck.. must be one
dialect.doublequote = True
return dialect
register_dialect("excel_semikolon", excel_semikolon)
-
diff --git a/openslides/utils/jsonfield/__init__.py b/openslides/utils/jsonfield/__init__.py
index b8d87c831..6dde401ce 100644
--- a/openslides/utils/jsonfield/__init__.py
+++ b/openslides/utils/jsonfield/__init__.py
@@ -1 +1,3 @@
-from fields import JSONField
\ No newline at end of file
+from fields import JSONField
+
+__all__ = ['JSONField']
diff --git a/openslides/utils/jsonfield/fields.py b/openslides/utils/jsonfield/fields.py
index 029ca74db..45c66aee4 100644
--- a/openslides/utils/jsonfield/fields.py
+++ b/openslides/utils/jsonfield/fields.py
@@ -6,6 +6,7 @@ from django.utils.translation import ugettext_lazy as _
from django.forms.fields import Field
from django.forms.util import ValidationError as FormValidationError
+
class JSONFormField(Field):
def clean(self, value):
@@ -21,6 +22,7 @@ class JSONFormField(Field):
raise FormValidationError(_("Enter valid JSON"))
return value
+
class JSONField(models.TextField):
"""JSONField is a generic textfield that serializes/unserializes JSON objects"""
diff --git a/openslides/utils/jsonfield/tests.py b/openslides/utils/jsonfield/tests.py
deleted file mode 100644
index 2eb87ec37..000000000
--- a/openslides/utils/jsonfield/tests.py
+++ /dev/null
@@ -1,108 +0,0 @@
-from django.db import models
-from django.test import TestCase
-from django.utils import simplejson as json
-
-from fields import JSONField
-
-
-class JsonModel(models.Model):
- json = JSONField()
-
-
-class ComplexEncoder(json.JSONEncoder):
- def default(self, obj):
- if isinstance(obj, complex):
- return {
- '__complex__': True,
- 'real': obj.real,
- 'imag': obj.imag,
- }
-
- return json.JSONEncoder.default(self, obj)
-
-
-def as_complex(dct):
- if '__complex__' in dct:
- return complex(dct['real'], dct['imag'])
- return dct
-
-
-class JSONModelCustomEncoders(models.Model):
- # A JSON field that can store complex numbers
- json = JSONField(
- dump_kwargs={'cls': ComplexEncoder},
- load_kwargs={'object_hook': as_complex},
- )
-
-
-class JSONFieldTest(TestCase):
- """JSONField Wrapper Tests"""
-
- def test_json_field_create(self):
- """Test saving a JSON object in our JSONField"""
-
- json_obj = {
- "item_1": "this is a json blah",
- "blergh": "hey, hey, hey"}
-
- obj = JsonModel.objects.create(json=json_obj)
- new_obj = JsonModel.objects.get(id=obj.id)
-
- self.failUnlessEqual(new_obj.json, json_obj)
-
- def test_json_field_modify(self):
- """Test modifying a JSON object in our JSONField"""
-
- json_obj_1 = {'a': 1, 'b': 2}
- json_obj_2 = {'a': 3, 'b': 4}
-
- obj = JsonModel.objects.create(json=json_obj_1)
-
- self.failUnlessEqual(obj.json, json_obj_1)
-
- obj.json = json_obj_2
-
- self.failUnlessEqual(obj.json, json_obj_2)
-
- obj.save()
-
- self.failUnlessEqual(obj.json, json_obj_2)
-
- self.assert_(obj)
-
- def test_json_field_load(self):
- """Test loading a JSON object from the DB"""
-
- json_obj_1 = {'a': 1, 'b': 2}
-
- obj = JsonModel.objects.create(json=json_obj_1)
-
- new_obj = JsonModel.objects.get(id=obj.id)
-
- self.failUnlessEqual(new_obj.json, json_obj_1)
-
- def test_json_list(self):
- """Test storing a JSON list"""
-
- json_obj = ["my", "list", "of", 1, "objs", {"hello": "there"}]
-
- obj = JsonModel.objects.create(json=json_obj)
- new_obj = JsonModel.objects.get(id=obj.id)
- self.failUnlessEqual(new_obj.json, json_obj)
-
- def test_empty_objects(self):
- """Test storing empty objects"""
-
- for json_obj in [{}, [], 0, '', False]:
- obj = JsonModel.objects.create(json=json_obj)
- new_obj = JsonModel.objects.get(id=obj.id)
- self.failUnlessEqual(json_obj, obj.json)
- self.failUnlessEqual(json_obj, new_obj.json)
-
- def test_custom_encoder(self):
- """Test encoder_cls and object_hook"""
- value = 1 + 3j # A complex number
-
- obj = JSONModelCustomEncoders.objects.create(json=value)
- new_obj = JSONModelCustomEncoders.objects.get(pk=obj.pk)
- self.failUnlessEqual(value, new_obj.json)
diff --git a/openslides/utils/modelfields.py b/openslides/utils/modelfields.py
index 72f63b51d..e3ccd1ef4 100644
--- a/openslides/utils/modelfields.py
+++ b/openslides/utils/modelfields.py
@@ -12,12 +12,13 @@
from django.db import models
+
class MinMaxIntegerField(models.IntegerField):
def __init__(self, min_value=None, max_value=None, *args, **kwargs):
self.min_value, self.max_value = min_value, max_value
super(MinMaxIntegerField, self).__init__(*args, **kwargs)
def formfield(self, **kwargs):
- defaults = {'min_value': self.min_value, 'max_value' : self.max_value}
+ defaults = {'min_value': self.min_value, 'max_value': self.max_value}
defaults.update(kwargs)
return super(MinMaxIntegerField, self).formfield(**defaults)
diff --git a/openslides/utils/pdf.py b/openslides/utils/pdf.py
index a50dfdcd4..4064f109e 100755
--- a/openslides/utils/pdf.py
+++ b/openslides/utils/pdf.py
@@ -28,16 +28,16 @@ from openslides.config.models import config
# register new truetype fonts
-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')))
+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
-PAGE_HEIGHT = defaultPageSize[1];
+PAGE_HEIGHT = defaultPageSize[1]
PAGE_WIDTH = defaultPageSize[0]
@@ -105,104 +105,104 @@ stylesheet.add(ParagraphStyle(
leftIndent=0,
spaceAfter=15,
))
-stylesheet.add(ParagraphStyle(name = 'Subitem',
- parent = stylesheet['Normal'],
- fontSize = 10,
- leading = 10,
- leftIndent = 20,
- spaceAfter = 15)
- )
-stylesheet.add(ParagraphStyle(name = 'Tablecell',
- parent = stylesheet['Normal'],
- fontSize = 9)
- )
-stylesheet.add(ParagraphStyle(name = 'Signaturefield',
- parent = stylesheet['Normal'],
- spaceBefore = 15)
+stylesheet.add(ParagraphStyle(
+ name='Subitem',
+ parent=stylesheet['Normal'],
+ fontSize=10,
+ leading=10,
+ leftIndent=20,
+ spaceAfter=15))
+stylesheet.add(ParagraphStyle(
+ name='Tablecell',
+ parent=stylesheet['Normal'],
+ fontSize=9))
+stylesheet.add(ParagraphStyle(name='Signaturefield',
+ parent=stylesheet['Normal'],
+ spaceBefore=15)
)
# Ballot stylesheets
-stylesheet.add(ParagraphStyle(name = 'Ballot_title',
- parent = stylesheet['Bold'],
- fontSize = 12,
- leading = 14,
- leftIndent = 30),
+stylesheet.add(ParagraphStyle(name='Ballot_title',
+ parent=stylesheet['Bold'],
+ fontSize=12,
+ leading=14,
+ leftIndent=30),
)
-stylesheet.add(ParagraphStyle(name = 'Ballot_subtitle',
- parent = stylesheet['Normal'],
- fontSize = 10,
- leading = 12,
- leftIndent = 30,
- rightIndent = 20,
- spaceAfter = 5),
+stylesheet.add(ParagraphStyle(name='Ballot_subtitle',
+ parent=stylesheet['Normal'],
+ fontSize=10,
+ leading=12,
+ leftIndent=30,
+ rightIndent=20,
+ spaceAfter=5),
)
-stylesheet.add(ParagraphStyle(name = 'Ballot_description',
- parent = stylesheet['Normal'],
- fontSize = 7,
- leading = 10,
- leftIndent = 30),
+stylesheet.add(ParagraphStyle(name='Ballot_description',
+ parent=stylesheet['Normal'],
+ fontSize=7,
+ leading=10,
+ leftIndent=30),
)
-stylesheet.add(ParagraphStyle(name = 'Ballot_option',
- parent = stylesheet['Normal'],
- fontSize = 12,
- leading = 24,
- leftIndent = 30),
+stylesheet.add(ParagraphStyle(name='Ballot_option',
+ parent=stylesheet['Normal'],
+ fontSize=12,
+ leading=24,
+ leftIndent=30),
)
-stylesheet.add(ParagraphStyle(name = 'Monotype',
- parent = stylesheet['Normal'],
- fontName = 'Courier',
- fontSize = 12,
- leading = 24,
- leftIndent = 30),
+stylesheet.add(ParagraphStyle(name='Monotype',
+ parent=stylesheet['Normal'],
+ fontName='Courier',
+ fontSize=12,
+ leading=24,
+ leftIndent=30),
)
-stylesheet.add(ParagraphStyle(name = 'Ballot_option_name',
- parent = stylesheet['Normal'],
- fontSize = 12,
- leading = 15,
- leftIndent = 30),
+stylesheet.add(ParagraphStyle(name='Ballot_option_name',
+ parent=stylesheet['Normal'],
+ fontSize=12,
+ leading=15,
+ leftIndent=30),
)
-stylesheet.add(ParagraphStyle(name = 'Ballot_option_group',
- parent = stylesheet['Normal'],
- fontSize = 8,
- leading = 15,
- leftIndent = 30),
+stylesheet.add(ParagraphStyle(name='Ballot_option_group',
+ parent=stylesheet['Normal'],
+ fontSize=8,
+ leading=15,
+ leftIndent=30),
)
-stylesheet.add(ParagraphStyle(name = 'Ballot_option_YNA',
- parent = stylesheet['Normal'],
- fontSize = 12,
- leading = 15,
- leftIndent = 49,
- spaceAfter = 18),
+stylesheet.add(ParagraphStyle(name='Ballot_option_YNA',
+ parent=stylesheet['Normal'],
+ fontSize=12,
+ leading=15,
+ leftIndent=49,
+ spaceAfter=18),
)
-stylesheet.add(ParagraphStyle(name = 'Ballot_option_group_right',
- parent = stylesheet['Normal'],
- fontSize = 8,
- leading = 16,
- leftIndent = 49),
+stylesheet.add(ParagraphStyle(name='Ballot_option_group_right',
+ parent=stylesheet['Normal'],
+ fontSize=8,
+ leading=16,
+ leftIndent=49),
)
-stylesheet.add(ParagraphStyle(name = 'Badge_title',
- parent = stylesheet['Bold'],
- fontSize = 16,
- leading = 22,
- leftIndent = 30),
+stylesheet.add(ParagraphStyle(name='Badge_title',
+ parent=stylesheet['Bold'],
+ fontSize=16,
+ leading=22,
+ leftIndent=30),
)
-stylesheet.add(ParagraphStyle(name = 'Badge_subtitle',
- parent = stylesheet['Normal'],
- fontSize = 12,
- leading = 24,
- leftIndent = 30),
+stylesheet.add(ParagraphStyle(name='Badge_subtitle',
+ parent=stylesheet['Normal'],
+ fontSize=12,
+ leading=24,
+ leftIndent=30),
)
stylesheet.add(ParagraphStyle(
- name = 'Badge_italic',
- parent = stylesheet['Italic'],
- fontSize = 12,
- leading = 24,
- leftIndent = 30,
+ name='Badge_italic',
+ parent=stylesheet['Italic'],
+ fontSize=12,
+ leading=24,
+ leftIndent=30,
))
stylesheet.add(ParagraphStyle(
- name = 'Badge_qrcode',
- fontSize = 12,
- leftIndent = 190,
+ name='Badge_qrcode',
+ fontSize=12,
+ leftIndent=190,
))
@@ -213,13 +213,13 @@ def firstPage(canvas, doc):
canvas.setFillGray(0.4)
title_line = u"%s | %s" % (config["event_name"],
- config["event_description"])
+ 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"]))
+ % (config["event_date"], config["event_location"]))
# time
canvas.setFont('Ubuntu', 7)
diff --git a/openslides/utils/person/__init__.py b/openslides/utils/person/__init__.py
index 7a69e8f25..e262022b4 100644
--- a/openslides/utils/person/__init__.py
+++ b/openslides/utils/person/__init__.py
@@ -11,11 +11,15 @@
"""
from openslides.utils.person.signals import receive_persons
-from openslides.utils.person.api import (generate_person_id, get_person,
- Person, Persons)
+from openslides.utils.person.api import (
+ generate_person_id, get_person, Person, Persons)
from openslides.utils.person.forms import PersonFormField, MultiplePersonFormField
from openslides.utils.person.models import PersonField, PersonMixin
+__all__ = ['receive_persons', 'generate_person_id', 'get_person', 'Person',
+ 'Persons', 'PersonFormField', 'MultiplePersonFormField',
+ 'PersonField', 'PersonMixin', 'EmptyPerson']
+
class EmptyPerson(PersonMixin):
@property
diff --git a/openslides/utils/person/forms.py b/openslides/utils/person/forms.py
index cee080bce..6cb19f3ab 100644
--- a/openslides/utils/person/forms.py
+++ b/openslides/utils/person/forms.py
@@ -61,8 +61,8 @@ class MultiplePersonFormField(PersonFormField):
widget = forms.widgets.SelectMultiple
def __init__(self, *args, **kwargs):
- super(MultiplePersonFormField, self).__init__(empty_label=None,
- *args, **kwargs)
+ super(MultiplePersonFormField, self).__init__(
+ empty_label=None, *args, **kwargs)
def to_python(self, value):
if hasattr(value, '__iter__'):
diff --git a/openslides/utils/template.py b/openslides/utils/template.py
index c3b16b630..5ed5eb778 100644
--- a/openslides/utils/template.py
+++ b/openslides/utils/template.py
@@ -10,8 +10,7 @@
:license: GNU GPL, see LICENSE for more details.
"""
-from django.http import HttpResponse
-from django.template import loader, Context, RequestContext, TextNode
+from django.template import loader, Context
from django.template.loader_tags import BlockNode, ExtendsNode
@@ -24,6 +23,10 @@ class Tab(object):
self.url = url
+## All following function are only needed to render a block from a template
+## and could be removed, if the template worked with an include-statement instead.
+## Its only used for ajax-request from the projector.
+
def get_template(template):
if isinstance(template, (tuple, list)):
return loader.select_template(template)
@@ -49,22 +52,22 @@ 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):
+ context_instance=None):
"""
Loads the given template_name and renders the given block with the given
dictionary as context. Returns a string.
@@ -77,23 +80,3 @@ def render_block_to_string(template_name, block, dictionary=None,
context_instance = Context(dictionary)
t.render(context_instance)
return render_template_block(t, block, context_instance)
-
-
-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 }}``.
- """
- if extra_context is None:
- extra_context = {}
- dictionary = {'params': kwargs}
- for key, value in extra_context.items():
- if callable(value):
- dictionary[key] = value()
- else:
- dictionary[key] = value
- c = RequestContext(request, dictionary)
- t = get_template(template)
- t.render(c)
- return HttpResponse(render_template_block(t, block, c), mimetype=mimetype)
diff --git a/openslides/utils/utils.py b/openslides/utils/utils.py
index 41aaf7544..d8f054eb0 100644
--- a/openslides/utils/utils.py
+++ b/openslides/utils/utils.py
@@ -10,12 +10,13 @@
:license: GNU GPL, see LICENSE for more details.
"""
+import sys
+
try:
import json
-except ImportError: # For python 2.5 support
+except ImportError: # For python 2.5 support
import simplejson as json
-from django.conf import settings
from django.contrib import messages
from django.contrib.auth.models import Permission
from django.core.context_processors import csrf
@@ -41,16 +42,17 @@ def gen_confirm_form(request, message, url):
Deprecated. Use Class base Views instead.
"""
- messages.warning(request,
- """
- %s
-
- """
- % (message, url, csrf(request)['csrf_token'], _("Yes"), _("No")))
+ messages.warning(
+ request,
+ """
+ %s
+
+ """
+ % (message, url, csrf(request)['csrf_token'], _("Yes"), _("No")))
def del_confirm_form(request, object, name=None, delete_link=None):
@@ -63,27 +65,28 @@ def del_confirm_form(request, object, name=None, delete_link=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 %s?')
+ gen_confirm_form(
+ request, _('Do you really want to delete %s?')
% html_strong(name), delete_link)
-def render_response(req, *args, **kwargs):
- kwargs['context_instance'] = RequestContext(req)
- return render_to_response(*args, **kwargs)
-
-
def template(template_name):
+ """
+ Decorator to set a template for a view.
+
+ Deprecated. Use class based views instead.
+ """
def renderer(func):
def wrapper(request, *args, **kwargs):
output = func(request, *args, **kwargs)
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
@@ -95,6 +98,8 @@ def permission_required(perm, login_url=None):
"""
Decorator for views that checks whether a user has a particular permission
enabled, redirecting to the log-in page if necessary.
+
+ Deprecated.
"""
def renderer(func):
def wrapper(request, *args, **kw):
@@ -107,10 +112,12 @@ def permission_required(perm, login_url=None):
return renderer
-def render_to_forbidden(request, error=
- ugettext_lazy("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_forbidden(request,
+ error=ugettext_lazy("Sorry, you have no rights to see this page.")):
+ # TODO: Integrate this function into the PermissionMixin once the
+ # above function is deleted.
+ return HttpResponseForbidden(render_to_string(
+ '403.html', {'error': error}, context_instance=RequestContext(request)))
def delete_default_permissions(**kwargs):
@@ -118,16 +125,18 @@ 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()
def ajax_request(data):
"""
generates a HTTPResponse-Object with json-Data for a
- ajax response
+ ajax response.
+
+ Deprecated.
"""
return HttpResponse(json.dumps(data))
diff --git a/openslides/utils/views.py b/openslides/utils/views.py
index 5e814bf9d..b9d1fc4b9 100644
--- a/openslides/utils/views.py
+++ b/openslides/utils/views.py
@@ -22,8 +22,7 @@ except ImportError:
# Is this exception realy necessary?
from StringIO import StringIO
-from reportlab.platypus import (SimpleDocTemplate, Paragraph, Frame, PageBreak,
- Spacer, Table, LongTable, TableStyle, Image)
+from reportlab.platypus import SimpleDocTemplate, Spacer
from reportlab.lib.units import cm
from django.contrib import messages
@@ -34,9 +33,9 @@ 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 _, ugettext_noop, ugettext_lazy
+from django.utils.translation import ugettext as _, ugettext_lazy
from django.utils.importlib import import_module
-from django.template import loader, RequestContext
+from django.template import RequestContext
from django.template.loader import render_to_string
from django.views.generic import (
TemplateView as _TemplateView,
@@ -50,8 +49,6 @@ from django.views.generic import (
from django.views.generic.detail import SingleObjectMixin
from django.views.generic.list import TemplateResponseMixin
-from openslides.config.models import config
-
from openslides.utils.utils import render_to_forbidden, html_strong
from openslides.utils.signals import template_manipulation
from openslides.utils.pdf import firstPage, laterPages
@@ -64,8 +61,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
@@ -90,8 +87,8 @@ class PermissionMixin(object):
if not self.has_permission(request, *args, **kwargs):
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_forbidden(request)
return _View.dispatch(self, request, *args, **kwargs)
@@ -130,18 +127,18 @@ class QuestionMixin(object):
option_fields = "\n".join([
'' % (option[0], unicode(option[1]))
for option in self.get_answer_options()])
- messages.warning(self.request,
+ messages.warning(
+ self.request,
"""
%(message)s
- """ % {
- 'message': self.get_question(),
- 'url': self.get_answer_url(),
- 'csrf': csrf(self.request)['csrf_token'],
- 'option_fields': option_fields})
+ """ % {'message': self.get_question(),
+ 'url': self.get_answer_url(),
+ 'csrf': csrf(self.request)['csrf_token'],
+ 'option_fields': option_fields})
def pre_post_redirect(self, request, *args, **kwargs):
# Reacts on the response of the user in a POST-request.
@@ -167,16 +164,16 @@ class QuestionMixin(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
@@ -217,8 +214,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):
@@ -235,8 +232,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):
@@ -256,8 +253,8 @@ 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):
@@ -299,7 +296,6 @@ class DeleteView(SingleObjectMixin, QuestionMixin, RedirectView):
class DetailView(TemplateView, SingleObjectMixin):
def get(self, request, *args, **kwargs):
self.object = self.get_object()
- context = self.get_context_data(object=self.object)
return super(DetailView, self).get(request, *args, **kwargs)
def get_context_data(self, **kwargs):
@@ -329,8 +325,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')
@@ -340,7 +336,7 @@ class PDFView(PermissionMixin, View):
buffer = StringIO()
pdf_document = self.get_template(buffer)
pdf_document.title = self.get_document_title()
- story = [Spacer(1, self.get_top_space()*cm)]
+ story = [Spacer(1, self.get_top_space() * cm)]
self.append_to_pdf(story)
@@ -351,9 +347,6 @@ class PDFView(PermissionMixin, View):
response.write(pdf)
return response
- def get_filename(self):
- return self.filename
-
def get(self, request, *args, **kwargs):
return self.render_to_response(self.get_filename())
@@ -364,9 +357,8 @@ def server_error(request, template_name='500.html'):
Templates: `500.html`
"""
- t = loader.get_template("500.html")
- return HttpResponseServerError(render_to_string('500.html',
- context_instance=RequestContext(request)))
+ return HttpResponseServerError(render_to_string(
+ template_name, context_instance=RequestContext(request)))
@receiver(template_manipulation, dispatch_uid="send_register_tab")
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 000000000..15fe79d8d
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,5 @@
+Django==1.4.2
+django-mptt
+reportlab
+PIL
+simplejson
diff --git a/setup.py b/setup.py
index 6b2911a46..ed1c3a018 100644
--- a/setup.py
+++ b/setup.py
@@ -12,15 +12,19 @@ from setuptools import find_packages
from openslides import get_version
+with open('README.txt') as file:
+ long_description = file.read()
+
setup(
name='openslides',
description='Presentation-System',
+ long_description=long_description,
version=get_version(),
url='http://openslides.org',
author='OpenSlides-Team',
author_email='support@openslides.org',
license='GPL2+',
- packages=find_packages(),
+ packages=find_packages(exclude=['tests']),
include_package_data = True,
classifiers = [
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/agenda/__init__.py b/tests/agenda/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/agenda/models.py b/tests/agenda/models.py
new file mode 100644
index 000000000..f61694356
--- /dev/null
+++ b/tests/agenda/models.py
@@ -0,0 +1,18 @@
+from django.db import models
+
+from openslides.projector.projector import SlideMixin
+from openslides.projector.api import register_slidemodel
+
+
+class ReleatedItem(SlideMixin, models.Model):
+ prefix = 'releateditem'
+
+ name = models.CharField(max_length='255')
+
+ def get_agenda_title(self):
+ return self.name
+
+ def get_agenda_title_supplement(self):
+ return 'test item'
+
+register_slidemodel(ReleatedItem)
diff --git a/openslides/agenda/tests.py b/tests/agenda/tests.py
similarity index 65%
rename from openslides/agenda/tests.py
rename to tests/agenda/tests.py
index ca56e009d..05c582f66 100644
--- a/openslides/agenda/tests.py
+++ b/tests/agenda/tests.py
@@ -12,12 +12,15 @@
from django.test import TestCase
from django.test.client import Client
-from django.contrib.auth.models import User
from django.db.models.query import EmptyQuerySet
from openslides.projector.api import get_active_slide
-
+from openslides.participant.models import User
from openslides.agenda.models import Item
+from openslides.agenda.slides import agenda_show
+
+from .models import ReleatedItem
+
class ItemTest(TestCase):
def setUp(self):
@@ -25,6 +28,8 @@ class ItemTest(TestCase):
self.item2 = Item.objects.create(title='item2')
self.item3 = Item.objects.create(title='item1A', parent=self.item1)
self.item4 = Item.objects.create(title='item1Aa', parent=self.item3)
+ self.releated = ReleatedItem.objects.create(name='foo')
+ self.item5 = Item.objects.create(title='item5', related_sid=self.releated.sid)
def testClosed(self):
self.assertFalse(self.item1.closed)
@@ -46,10 +51,6 @@ class ItemTest(TestCase):
self.assertTrue(self.item3 in self.item1.get_children())
self.assertFalse(self.item4 in self.item1.get_children())
- l = Item.objects.all()
- self.assertEqual(str(l),
- "[, , , ]")
-
def testForms(self):
for item in Item.objects.all():
initial = item.weight_form.initial
@@ -64,6 +65,36 @@ class ItemTest(TestCase):
self.item1.related_sid = 'foobar'
self.assertFalse(self.item1.get_related_slide() is None)
+ def test_title_supplement(self):
+ self.assertEqual(self.item1.get_title_supplement(), '')
+
+ def test_delete_item(self):
+ new_item1 = Item.objects.create()
+ new_item2 = Item.objects.create(parent=new_item1)
+ new_item3 = Item.objects.create(parent=new_item2)
+ new_item1.delete()
+ self.assertTrue(new_item3 in Item.objects.all())
+ new_item2.delete(with_children=True)
+ self.assertFalse(new_item3 in Item.objects.all())
+
+ def test_absolute_url(self):
+ self.assertEqual(self.item1.get_absolute_url(), '/agenda/1/')
+ self.assertEqual(self.item1.get_absolute_url('edit'), '/agenda/1/edit/')
+ self.assertEqual(self.item1.get_absolute_url('delete'), '/agenda/1/del/')
+
+ def test_agenda_slide(self):
+ data = agenda_show()
+ self.assertEqual(list(data['items']), list(Item.objects.all().filter(parent=None)))
+ self.assertEqual(data['template'], 'projector/AgendaSummary.html')
+ self.assertEqual(data['title'], 'Agenda')
+
+ def test_releated_item(self):
+ self.assertEqual(self.item5.get_title(), self.releated.name)
+ self.assertEqual(self.item5.get_title_supplement(), 'test item')
+ self.assertEqual(self.item5.get_related_type(), 'releateditem')
+ self.assertEqual(self.item5.print_related_type(), 'Releateditem')
+
+
class ViewTest(TestCase):
def setUp(self):
@@ -71,8 +102,10 @@ class ViewTest(TestCase):
self.item2 = Item.objects.create(title='item2')
self.refreshItems()
- self.admin = User.objects.create_user('testadmin', '', 'default')
- self.anonym = User.objects.create_user('testanoym', '', 'default')
+ self.admin, created = User.objects.get_or_create(username='testadmin')
+ self.anonym, created = User.objects.get_or_create(username='testanonym')
+ self.admin.reset_password('default')
+ self.anonym.reset_password('default')
self.admin.is_superuser = True
self.admin.save()
@@ -91,6 +124,13 @@ class ViewTest(TestCase):
def anonymClient(self):
return Client()
+ def testOverview(self):
+ c = self.adminClient
+
+ response = c.get('/agenda/')
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(len(response.context['items']), len(Item.objects.all()))
+
def testActivate(self):
c = self.adminClient
@@ -122,6 +162,14 @@ class ViewTest(TestCase):
self.refreshItems()
self.assertEqual(response.status_code, 404)
+ # Test ajax
+ response = c.get('/agenda/%d/close/' % self.item1.id,
+ HTTP_X_REQUESTED_WITH='XMLHttpRequest')
+ self.assertEqual(response.status_code, 200)
+ response = c.get('/agenda/%d/open/' % self.item1.id,
+ HTTP_X_REQUESTED_WITH='XMLHttpRequest')
+ self.assertEqual(response.status_code, 200)
+
def testEdit(self):
c = self.adminClient
@@ -131,7 +179,7 @@ class ViewTest(TestCase):
response = c.get('/agenda/%d/edit/' % 1000)
self.assertEqual(response.status_code, 404)
- data = {'title': 'newitem1', 'text': 'item1-text', 'weight':'0'}
+ data = {'title': 'newitem1', 'text': 'item1-text', 'weight': '0'}
response = c.post('/agenda/%d/edit/' % self.item1.id, data)
self.assertEqual(response.status_code, 302)
self.refreshItems()
@@ -143,4 +191,3 @@ class ViewTest(TestCase):
self.assertEqual(response.status_code, 200)
self.refreshItems()
self.assertEqual(self.item1.title, 'newitem1')
-
diff --git a/tests/test_init.py b/tests/test_init.py
new file mode 100644
index 000000000..6155716f1
--- /dev/null
+++ b/tests/test_init.py
@@ -0,0 +1,23 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+ Unit test for OpenSlides __init__.py
+
+ :copyright: 2011, 2012 by OpenSlides team, see AUTHORS.
+ :license: GNU GPL, see LICENSE for more details.
+"""
+
+from django.test import TestCase
+
+from openslides import get_version
+
+class InitTest(TestCase):
+ def test_get_version(self):
+ self.assertEqual(get_version((1, 3, 0, 'beta', 2)), '1.3-beta2')
+ self.assertEqual(get_version((1, 0, 0, 'final', 0)), '1.0')
+ self.assertEqual(get_version((2, 5, 3, 'alpha', 0)), '2.5.3-alpha0')
+ git_version = get_version((2, 5, 0, 'dev', 0))
+ if 'unknown' in git_version:
+ self.assertEqual(len(git_version), 14)
+ else:
+ self.assertEqual(len(git_version), 47)
diff --git a/openslides/motion/tests.py b/tests/test_motion.py
similarity index 92%
rename from openslides/motion/tests.py
rename to tests/test_motion.py
index 1fb387951..26c506c37 100644
--- a/openslides/motion/tests.py
+++ b/tests/test_motion.py
@@ -11,10 +11,10 @@
"""
from django.test import TestCase
-from django.test.client import Client
from openslides.participant.models import User
-from openslides.motion.models import Motion, AVersion
+from openslides.motion.models import Motion
+
class MotionTest(TestCase):
def setUp(self):
@@ -39,4 +39,3 @@ class MotionTest(TestCase):
self.assertEqual(self.app1.versions.count(), 2)
self.assertEqual(self.app1.last_version, self.app1.versions[1])
-
diff --git a/openslides/participant/tests.py b/tests/test_participant.py
similarity index 92%
rename from openslides/participant/tests.py
rename to tests/test_participant.py
index 10013b877..4227dc66b 100644
--- a/openslides/participant/tests.py
+++ b/tests/test_participant.py
@@ -11,8 +11,6 @@
"""
from django.test import TestCase
-from django.test.client import Client
-from django.contrib.auth.hashers import check_password
from openslides.utils.person import get_person, Persons
from openslides.participant.api import gen_username, gen_password
@@ -38,9 +36,9 @@ class UserTest(TestCase):
self.assertEqual(unicode(self.user1), 'Max Mustermann')
def test_name_suffix(self):
- self.user1.structure_level = 'München'
+ self.user1.structure_level = u'München'
self.user1.save()
- self.assertEqual(unicode(self.user1), 'Max Mustermann (München)')
+ self.assertEqual(unicode(self.user1), u'Max Mustermann (München)')
def test_reset_password(self):
self.assertIsInstance(self.user1.default_password, basestring)