rename some user api and participant names

This commit is contained in:
Oskar Hahn 2012-08-07 22:43:57 +02:00
parent b55ceddb82
commit 1719aa588d
21 changed files with 334 additions and 369 deletions

View File

@ -38,7 +38,7 @@
[
"can_see_participant",
"participant",
"profile"
"openslidesuser"
],
[
"can_see_projector",
@ -92,7 +92,7 @@
[
"can_see_participant",
"participant",
"profile"
"openslidesuser"
],
[
"can_see_projector",
@ -161,12 +161,12 @@
[
"can_manage_participant",
"participant",
"profile"
"openslidesuser"
],
[
"can_see_participant",
"participant",
"profile"
"openslidesuser"
],
[
"can_manage_projector",
@ -195,12 +195,12 @@
[
"can_manage_participant",
"participant",
"profile"
"openslidesuser"
],
[
"can_see_participant",
"participant",
"profile"
"openslidesuser"
],
[
"can_see_projector",

View File

@ -11,32 +11,13 @@
"""
from django import forms
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _, ugettext_noop
from openslides.utils.forms import CssClassMixin
from openslides.utils.user import UserFormField, MultipleUserFormField
from openslides.utils.person import PersonFormField, MultiplePersonFormField
from openslides.application.models import Application
class UserModelChoiceField(forms.ModelChoiceField):
"""
Extend ModelChoiceField for users so that the choices are
listed as 'first_name last_name' instead of just 'username'.
"""
def label_from_instance(self, obj):
return obj.get_full_name()
class UserModelMultipleChoiceField(forms.ModelMultipleChoiceField):
"""
Extend ModelMultipleChoiceField for users so that the choices are
listed as 'first_name last_name' instead of just 'username'.
"""
def label_from_instance(self, obj):
return obj.get_full_name()
class ApplicationForm(forms.Form, CssClassMixin):
title = forms.CharField(widget=forms.TextInput(), label=_("Title"))
text = forms.CharField(widget=forms.Textarea(), label=_("Text"))
@ -51,7 +32,7 @@ class ApplicationFormTrivialChanges(ApplicationForm):
class ApplicationManagerForm(forms.ModelForm, CssClassMixin):
submitter = UserFormField()
submitter = PersonFormField()
class Meta:
model = Application
@ -60,7 +41,7 @@ class ApplicationManagerForm(forms.ModelForm, CssClassMixin):
class ApplicationManagerFormSupporter(ApplicationManagerForm):
# TODO: Do not show the submitter in the user-list
supporter = MultipleUserFormField(required=False, label=_("Supporters"))
supporter = MultiplePersonFormField(required=False, label=_("Supporters"))
class ApplicationImportForm(forms.Form, CssClassMixin):

View File

@ -21,12 +21,12 @@ from django.utils.translation import pgettext
from django.utils.translation import ugettext_lazy as _, ugettext_noop, ugettext
from openslides.utils.utils import _propper_unicode
from openslides.utils.user import UserField
from openslides.utils.person import PersonField
from openslides.config.models import config
from openslides.config.signals import default_config_value
from openslides.participant.models import Profile
from openslides.participant.models import OpenSlidesUser
from openslides.poll.models import (BaseOption, BasePoll, CountVotesCast,
CountInvalid, BaseVote)
@ -39,7 +39,7 @@ from openslides.agenda.models import Item
class ApplicationSupporter(models.Model):
application = models.ForeignKey("Application")
user = UserField()
person = PersonField()
class Application(models.Model, SlideMixin):
@ -66,7 +66,7 @@ class Application(models.Model, SlideMixin):
# genpoll
)
submitter = UserField(verbose_name=_("Submitter"))
submitter = PersonField(verbose_name=_("Submitter"))
number = models.PositiveSmallIntegerField(blank=True, null=True,
unique=True)
status = models.CharField(max_length=3, choices=STATUS, default='pub')
@ -163,10 +163,11 @@ class Application(models.Model, SlideMixin):
@property
def supporters(self):
return [object.user for object in self.applicationsupporter_set.all()]
for object in self.applicationsupporter_set.all():
yield object.person
def is_supporter(self, user):
return self.applicationsupporter_set.filter(user=user).exists()
def is_supporter(self, person):
return self.applicationsupporter_set.filter(person=person).exists()
@property
def enough_supporters(self):
@ -251,20 +252,20 @@ class Application(models.Model, SlideMixin):
self.save()
self.writelog(_("Status reseted to: %s") % (self.get_status_display()), user)
def support(self, user):
def support(self, person):
"""
Add a Supporter to the list of supporters of the application.
"""
if user == self.submitter:
if person == self.submitter:
# TODO: Use own Exception
raise NameError('Supporter can not be the submitter of a ' \
'application.')
if self.permitted is not None:
# TODO: Use own Exception
raise NameError('This application is already permitted.')
if not self.is_supporter(user):
ApplicationSupporter(application=self, user=user).save()
self.writelog(_("Supporter: +%s") % (user))
if not self.is_supporter(person):
ApplicationSupporter(application=self, person=person).save()
self.writelog(_("Supporter: +%s") % (person))
def unsupport(self, user):
"""
@ -362,8 +363,8 @@ class Application(models.Model, SlideMixin):
is_admin = False
if user:
try:
user = user.profile
except Profile.DoesNotExist:
user = user.openslidesuser
except OpenSlidesUser.DoesNotExist:
is_admin = True
except AttributeError:
# For the anonymous-user

View File

@ -42,7 +42,7 @@ from openslides.utils.template import Tab
from openslides.utils.utils import (template, permission_required,
del_confirm_form, gen_confirm_form)
from openslides.utils.views import PDFView, RedirectView, DeleteView, FormView
from openslides.utils.user import get_user
from openslides.utils.person import get_person
from openslides.config.models import config
@ -50,8 +50,8 @@ from openslides.projector.projector import Widget
from openslides.poll.views import PollFormView
from openslides.participant.api import gen_username, gen_password, user2djangouser
from openslides.participant.models import Profile
from openslides.participant.api import gen_username, gen_password
from openslides.participant.models import OpenSlidesUser
from openslides.agenda.models import Item
@ -124,7 +124,7 @@ def overview(request):
for (i, application) in enumerate(applications):
try:
applications[i] = {
'actions' : application.get_allowed_actions(user2djangouser(request.user)),
'actions' : application.get_allowed_actions(request.user.openslidesuser),
'application' : application
}
except:
@ -152,7 +152,7 @@ def view(request, application_id, newest=False):
else:
version = application.public_version
revisions = application.versions
user = user2djangouser(request.user)
user = request.user.openslidesuser
actions = application.get_allowed_actions(user=user)
return {
@ -183,11 +183,11 @@ def edit(request, application_id=None):
if application_id is not None:
application = Application.objects.get(id=application_id)
if (not hasattr(application.submitter, 'user') or
not user2djangouser(request.user) == application.submitter.user) \
not request.user.openslidesuser == application.submitter.user) \
and not is_manager:
messages.error(request, _("You can not edit this application. You are not the submitter."))
return redirect(reverse('application_view', args=[application.id]))
actions = application.get_allowed_actions(user=user2djangouser(request.user))
actions = application.get_allowed_actions(user=request.user.openslidesuser)
else:
application = None
actions = None
@ -221,7 +221,7 @@ def edit(request, application_id=None):
original_supporters = []
application = managerform.save(commit=False)
elif application_id is None:
application = Application(submitter=user2djangouser(request.user))
application = Application(submitter=request.user.openslidesuser)
application.title = dataform.cleaned_data['title']
application.text = dataform.cleaned_data['text']
application.reason = dataform.cleaned_data['reason']
@ -231,7 +231,7 @@ def edit(request, application_id=None):
and dataform.cleaned_data['trivial_change']
except KeyError:
trivial_change = False
application.save(user2djangouser(request.user), trivial_change=trivial_change)
application.save(request.user.openslidesuser, trivial_change=trivial_change)
if is_manager:
try:
new_supporters = set(managerform.cleaned_data['supporter'])
@ -273,10 +273,10 @@ def edit(request, application_id=None):
dataform = formclass(initial=initial, prefix="data")
if is_manager:
if application_id is None:
initial = {'submitter': user2djangouser(request.user).uid}
initial = {'submitter': request.user.openslidesuser.person_id}
else:
initial = {'submitter': application.submitter.uid,
'supporter': [supporter.uid for supporter in application.supporters]}
initial = {'submitter': application.submitter.person_id,
'supporter': [supporter.person_id for supporter in application.supporters]}
managerform = managerformclass(initial=initial,
instance=application, prefix="manager")
else:
@ -296,7 +296,7 @@ def set_number(request, application_id):
set a number for an application.
"""
try:
Application.objects.get(pk=application_id).set_number(user=user2djangouser(request.user))
Application.objects.get(pk=application_id).set_number(user=request.user.openslidesuser)
messages.success(request, _("Application number was successfully set."))
except Application.DoesNotExist:
pass
@ -312,7 +312,7 @@ def permit(request, application_id):
permit an application.
"""
try:
Application.objects.get(pk=application_id).permit(user=user2djangouser(request.user))
Application.objects.get(pk=application_id).permit(user=request.user.openslidesuser)
messages.success(request, _("Application was successfully permitted."))
except Application.DoesNotExist:
pass
@ -327,7 +327,7 @@ def notpermit(request, application_id):
reject (not permit) an application.
"""
try:
Application.objects.get(pk=application_id).notpermit(user=user2djangouser(request.user))
Application.objects.get(pk=application_id).notpermit(user=request.user.openslidesuser)
messages.success(request, _("Application was successfully rejected."))
except Application.DoesNotExist:
pass
@ -343,7 +343,7 @@ def set_status(request, application_id=None, status=None):
try:
if status is not None:
application = Application.objects.get(pk=application_id)
application.set_status(user=user2djangouser(request.user), status=status)
application.set_status(user=request.user.openslidesuser, status=status)
messages.success(request, _("Application status was set to: <b>%s</b>.") % application.get_status_display())
except Application.DoesNotExist:
pass
@ -359,7 +359,7 @@ def reset(request, application_id):
reset an application.
"""
try:
Application.objects.get(pk=application_id).reset(user=user2djangouser(request.user))
Application.objects.get(pk=application_id).reset(user=request.user.openslides.user)
messages.success(request, _("Application status was reset.") )
except Application.DoesNotExist:
pass
@ -373,7 +373,7 @@ def support(request, application_id):
support an application.
"""
try:
Application.objects.get(pk=application_id).support(user=user2djangouser(request.user))
Application.objects.get(pk=application_id).support(user=request.user.openslides.user)
messages.success(request, _("You have support the application successfully.") )
except Application.DoesNotExist:
pass
@ -387,7 +387,7 @@ def unsupport(request, application_id):
unsupport an application.
"""
try:
Application.objects.get(pk=application_id).unsupport(user=user2djangouser(request.user))
Application.objects.get(pk=application_id).unsupport(user=request.user.openslidesuser)
messages.success(request, _("You have unsupport the application successfully.") )
except Application.DoesNotExist:
pass
@ -401,7 +401,7 @@ def gen_poll(request, application_id):
gen a poll for this application.
"""
try:
poll = Application.objects.get(pk=application_id).gen_poll(user=user2djangouser(request.user))
poll = Application.objects.get(pk=application_id).gen_poll(user=request.user.openslidesuser)
messages.success(request, _("New vote was successfully created.") )
except Application.DoesNotExist:
pass # TODO: do not call poll after this excaption
@ -418,7 +418,7 @@ def delete_poll(request, poll_id):
count = application.polls.filter(id__lte=poll_id).count()
if request.method == 'POST':
poll.delete()
application.writelog(_("Poll deleted"), user2djangouser(request.user))
application.writelog(_("Poll deleted"), request.user.openslidesuser)
messages.success(request, _('Poll was successfully deleted.'))
else:
del_confirm_form(request, poll, name=_("the %s. poll") % count, delete_link=reverse('application_poll_delete', args=[poll_id]))
@ -458,7 +458,7 @@ class ApplicationDelete(DeleteView):
if len(self.applications):
for application in self.applications:
if not 'delete' in application.get_allowed_actions(user=user2djangouser(request.user)):
if not 'delete' in application.get_allowed_actions(user=request.user.openslidesuser):
messages.error(request, _("You can not delete application <b>%s</b>.") % application)
continue
@ -467,7 +467,7 @@ class ApplicationDelete(DeleteView):
messages.success(request, _("Application <b>%s</b> was successfully deleted.") % title)
elif self.object:
if not 'delete' in self.object.get_allowed_actions(user=user2djangouser(request.user)):
if not 'delete' in self.object.get_allowed_actions(user=request.user.openslidesuser):
messages.error(request, _("You can not delete application <b>%s</b>.") % self.object)
else:
title = self.object.title
@ -508,12 +508,12 @@ class ViewPoll(PollFormView):
self.application = self.poll.get_application()
context['application'] = self.application
context['ballot'] = self.poll.get_ballot()
context['actions'] = self.application.get_allowed_actions(user=user2djangouser(self.request.user))
context['actions'] = self.application.get_allowed_actions(user=self.request.user.openslidesuser)
return context
def get_modelform_class(self):
cls = super(ViewPoll, self).get_modelform_class()
user = user2djangouser(self.request.user)
user = self.request.user.openslidesuser
class ViewPollFormClass(cls):
def save(self, commit = True):
@ -535,7 +535,7 @@ def permit_version(request, aversion_id):
aversion = AVersion.objects.get(pk=aversion_id)
application = aversion.application
if request.method == 'POST':
application.accept_version(aversion, user=user2djangouser(request.user))
application.accept_version(aversion, user=request.user.openslidesuser)
messages.success(request, _("Version <b>%s</b> accepted.") % (aversion.aid))
else:
gen_confirm_form(request, _('Do you really want to permit version <b>%s</b>?') % aversion.aid, reverse('application_version_permit', args=[aversion.id]))
@ -547,7 +547,7 @@ def reject_version(request, aversion_id):
aversion = AVersion.objects.get(pk=aversion_id)
application = aversion.application
if request.method == 'POST':
if application.reject_version(aversion, user=user2djangouser(request.user)):
if application.reject_version(aversion, user=request.user.openslidesuser):
messages.success(request, _("Version <b>%s</b> rejected.") % (aversion.aid))
else:
messages.error(request, _("ERROR by rejecting the version.") )
@ -560,8 +560,8 @@ def reject_version(request, aversion_id):
@template('application/import.html')
def application_import(request):
try:
request.user.profile
except Profile.DoesNotExist:
request.user.openslidesuser
except OpenSlidesUser.DoesNotExist:
pass
except AttributeError:
# AnonymousUser

View File

@ -14,7 +14,7 @@ from django import forms
from django.utils.translation import ugettext_lazy as _, ugettext_noop
from openslides.utils.forms import CssClassMixin
from openslides.utils.user import UserFormField
from openslides.utils.person import PersonFormField
from openslides.assignment.models import Assignment
@ -29,7 +29,7 @@ class AssignmentForm(forms.ModelForm, CssClassMixin):
class AssignmentRunForm(forms.Form, CssClassMixin):
candidate = UserFormField(
candidate = PersonFormField(
widget=forms.Select(attrs={'class': 'medium-input'}),
label=_("Nominate a participant"),
)

View File

@ -15,7 +15,7 @@ from django.db import models
from django.dispatch import receiver
from django.utils.translation import ugettext_lazy as _, ugettext_noop
from openslides.utils.user import UserField
from openslides.utils.person import PersonField
from openslides.config.models import config
from openslides.config.signals import default_config_value
@ -31,11 +31,11 @@ from openslides.agenda.models import Item
class AssignmentCandidate(models.Model):
assignment = models.ForeignKey("Assignment")
user = UserField(db_index=True)
person = PersonField(db_index=True)
elected = models.BooleanField(default=False)
def __unicode__(self):
return unicode(self.user)
return unicode(self.person)
class Assignment(models.Model, SlideMixin):
@ -69,7 +69,7 @@ class Assignment(models.Model, SlideMixin):
self.status = status
self.save()
def run(self, candidate, user=None):
def run(self, candidate, person=None):
"""
run for a vote
"""
@ -77,22 +77,22 @@ class Assignment(models.Model, SlideMixin):
# Use other Exceptions
if self.is_candidate(candidate):
raise NameError(_('<b>%s</b> is already a candidate.') % candidate)
if not user.has_perm("assignment.can_manage_assignment") and self.status != 'sea':
if not person.has_perm("assignment.can_manage_assignment") and self.status != 'sea':
raise NameError(_('The candidate list is already closed.'))
AssignmentCandidate(assignment=self, user=candidate, elected=False).save()
AssignmentCandidate(assignment=self, person=candidate, elected=False).save()
def delrun(self, candidate):
"""
stop running for a vote
"""
if self.is_candidate(candidate):
self.assignment_candidats.get(user=candidate).delete()
self.assignment_candidats.get(person=candidate).delete()
else:
# TODO: Use an OpenSlides Error
raise Exception(_('%s is no candidate') % candidate)
def is_candidate(self, user):
if self.assignment_candidats.filter(user=user).exists():
def is_candidate(self, person):
if self.assignment_candidats.filter(person=person).exists():
return True
else:
return False
@ -122,23 +122,22 @@ class Assignment(models.Model, SlideMixin):
if only_candidate:
candidates = candidates.filter(elected=False)
return [candidate.user for candidate in candidates]
#for candidate in candidates:
# yield candidate.user
for candidate in candidates.all():
yield candidate.person
def set_elected(self, user, value=True):
candidate = self.assignment_candidats.get(user=user)
def set_elected(self, person, value=True):
candidate = self.assignment_candidats.get(person=person)
candidate.elected = value
candidate.save()
def is_elected(self, user):
return user in self.elected
def is_elected(self, person):
return person in self.elected
def gen_poll(self):
poll = AssignmentPoll(assignment=self)
poll.save()
poll.set_options([{'candidate': user} for user in self.candidates])
poll.set_options([{'candidate': person} for person in self.candidates])
return poll
@ -228,7 +227,7 @@ class AssignmentVote(BaseVote):
class AssignmentOption(BaseOption):
poll = models.ForeignKey('AssignmentPoll')
candidate = UserField()
candidate = PersonField()
vote_class = AssignmentVote
def __unicode__(self):

View File

@ -35,12 +35,12 @@
<h3>{% trans "Candidates" %}</h3>
<ol>
{% for user in assignment.candidates %}
{% for person in assignment.candidates %}
<li>
{{ user }}
{{ person }}
{% if perms.assignment.can_manage_assignment %}
{% if assignment.status == "sea" or assignment.status == "vot" %}
<a href="{% url assignment_delother assignment.id user.uid %}"><img src="{% static 'images/icons/delete.png' %}" title="{% trans 'Remove candidate' %}"></a>
<a href="{% url assignment_delother assignment.id person.person_id %}"><img src="{% static 'images/icons/delete.png' %}" title="{% trans 'Remove candidate' %}"></a>
{% endif %}
{% endif %}
</li>
@ -137,7 +137,7 @@
<td class="candidate">
{% if candidate in assignment.elected %}
{% if perms.assignment.can_manage_assignment %}
<a class="election_link elected" href='{% url assignment_user_not_elected assignment.id candidate.uid %}'></a>
<a class="election_link elected" href='{% url assignment_user_not_elected assignment.id candidate.person_id %}'></a>
{% else %}
<a class="elected">
<img src="{% static 'images/icons/voting-yes.png' %}" title="{% trans 'Candidate is elected' %}">
@ -145,7 +145,7 @@
{% endif %}
{% else %}
{% if perms.assignment.can_manage_assignment %}
<a class="election_link" href='{% url assignment_user_elected assignment.id candidate.uid %}'></a>
<a class="election_link" href='{% url assignment_user_elected assignment.id candidate.person_id %}'></a>
{% endif %}
{% endif %}
{{ candidate }}

View File

@ -30,12 +30,11 @@ from openslides.utils.template import Tab
from openslides.utils.utils import (template, permission_required,
gen_confirm_form, del_confirm_form, ajax_request)
from openslides.utils.views import FormView, DeleteView, PDFView, RedirectView
from openslides.utils.user import get_user
from openslides.utils.person import get_person
from openslides.config.models import config
from openslides.participant.models import Profile
from openslides.participant.api import user2djangouser
from openslides.participant.models import OpenSlidesUser
from openslides.projector.projector import Widget
@ -98,7 +97,7 @@ def view(request, assignment_id=None):
polls = assignment.poll_set.all()
vote_results = assignment.vote_results(only_published=False)
user = user2djangouser(request.user)
user = request.user.openslidesuser
return {
'assignment': assignment,
'form': form,
@ -174,7 +173,7 @@ def set_status(request, assignment_id=None, status=None):
def run(request, assignment_id):
assignment = Assignment.objects.get(pk=assignment_id)
try:
assignment.run(user2djangouser(request.user), request.user)
assignment.run(request.user.openslidesuser, request.user)
messages.success(request, _('You have set your candidature successfully.') )
except NameError, e:
messages.error(request, e)
@ -186,7 +185,7 @@ def delrun(request, assignment_id):
assignment = Assignment.objects.get(pk=assignment_id)
try:
if assignment.status == 'sea' or user.has_perm("assignment.can_manage_assignment"):
assignment.delrun(user2djangouser(request.user))
assignment.delrun(request.user.openslidesuser)
else:
messages.error(request, _('The candidate list is already closed.'))
except Exception, e:
@ -199,19 +198,19 @@ def delrun(request, assignment_id):
@permission_required('assignment.can_manage_assignment')
def delother(request, assignment_id, user_id):
assignment = Assignment.objects.get(pk=assignment_id)
user = get_user(user_id)
person = get_person(user_id)
if request.method == 'POST':
try:
assignment.delrun(user)
assignment.delrun(person)
except Exception, e:
messages.error(request, e)
else:
messages.success(request, _("Candidate <b>%s</b> was withdrawn successfully.") % (user))
messages.success(request, _("Candidate <b>%s</b> was withdrawn successfully.") % (person))
else:
gen_confirm_form(request,
_("Do you really want to withdraw <b>%s</b> from the election?") \
% user, reverse('assignment_delother', args=[assignment_id, user_id]))
% person, reverse('assignment_delother', args=[assignment_id, user_id]))
return redirect(reverse('assignment_view', args=[assignment_id]))
@ -273,15 +272,15 @@ def set_publish_status(request, poll_id):
@permission_required('assignment.can_manage_assignment')
def set_elected(request, assignment_id, user_id, elected=True):
assignment = Assignment.objects.get(pk=assignment_id)
user = get_user(user_id)
assignment.set_elected(user, elected)
person = get_person(user_id)
assignment.set_elected(person, elected)
if request.is_ajax():
if elected:
link = reverse('assignment_user_not_elected', args=[assignment.id, user.uid])
link = reverse('assignment_user_not_elected', args=[assignment.id, person.person_id])
text = _('not elected')
else:
link = reverse('assignment_user_elected', args=[assignment.id, user.uid])
link = reverse('assignment_user_elected', args=[assignment.id, person.person_id])
text = _('elected')
return ajax_request({'elected': elected, 'link': link, 'text': text})
@ -554,8 +553,8 @@ class AssignmentPollPDF(PDFView):
candidate = option.candidate
cell.append(Paragraph(candidate.user.get_full_name(),
stylesheet['Ballot_option_name']))
if candidate.group:
cell.append(Paragraph("(%s)" % candidate.group,
if candidate.name_surfix:
cell.append(Paragraph("(%s)" % candidate.name_surfix,
stylesheet['Ballot_option_group']))
else:
cell.append(Paragraph("&nbsp;",

View File

@ -21,7 +21,6 @@ def _fs2unicode(s):
SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
AUTH_PROFILE_MODULE = 'participant.Profile'
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',
'openslides.utils.auth.AnonymousAuth',)
@ -124,6 +123,7 @@ INSTALLED_APPS = (
'django.contrib.messages',
'django.contrib.staticfiles',
'mptt',
'openslides.utils',
'openslides.poll',
'openslides.projector',
'openslides.agenda',

View File

@ -15,8 +15,8 @@ import string
from django.contrib.auth.models import User
from openslides.utils.user import get_user
from openslides.participant.models import Profile
from openslides.utils.person import get_person
from openslides.participant.models import OpenSlidesUser
def gen_password():
@ -47,11 +47,3 @@ def gen_username(first_name, last_name):
User.objects.get(username=testname)
except User.DoesNotExist:
return testname
def user2djangouser(user):
u = get_user('djangouser:%d' % user.id)
try:
return u.profile
except Profile.DoesNotExist:
return u

View File

@ -17,7 +17,7 @@ from django.utils.translation import ugettext_lazy as _, ugettext_noop
from openslides.utils.forms import CssClassMixin, LocalizedModelMultipleChoiceField
from openslides.participant.models import Profile
from openslides.participant.models import OpenSlidesUser
USER_APPLICATION_IMPORT_OPTIONS = [
@ -62,9 +62,9 @@ class UsernameForm(forms.ModelForm, CssClassMixin):
'date_joined', 'user_permissions')
class ProfileForm(forms.ModelForm, CssClassMixin):
class OpenSlidesUserForm(forms.ModelForm, CssClassMixin):
class Meta:
model = Profile
model = OpenSlidesUser
class GroupForm(forms.ModelForm, CssClassMixin):

View File

@ -12,18 +12,18 @@
from django.contrib.auth.models import User, Group
from django.db import models
from django.db.models import Q
from django.db.models import Q, signals
from django.dispatch import receiver
from django.utils.translation import ugettext_lazy as _, ugettext_noop
from openslides.utils.user import UserMixin
from openslides.utils.user.signals import receiv_users
from openslides.utils.person import PersonMixin
from openslides.utils.person.signals import receiv_persons
from openslides.config.signals import default_config_value
class Profile(models.Model, UserMixin):
user_prefix = 'participant'
class OpenSlidesUser(models.Model, PersonMixin):
person_prefix = 'openslides_user'
GENDER_CHOICES = (
('male', _('Male')),
('female', _('Female')),
@ -36,8 +36,8 @@ class Profile(models.Model, UserMixin):
)
user = models.OneToOneField(User, unique=True, editable=False)
group = models.CharField(max_length=100, null=True, blank=True,
verbose_name = _("Group"), help_text=_('Shown behind the name.'))
name_surfix = models.CharField(max_length=100, null=True, blank=True,
verbose_name = _("Name Surfix"), help_text=_('Shown behind the name.'))
gender = models.CharField(max_length=50, choices=GENDER_CHOICES, blank=True,
verbose_name = _("Gender"),
help_text=_('Only for filter the userlist.'))
@ -76,76 +76,56 @@ class Profile(models.Model, UserMixin):
return ('user_delete', [str(self.user.id)])
def __unicode__(self):
if self.group:
return "%s (%s)" % (self.user.get_full_name(), self.group)
if self.name_surfix:
return "%s (%s)" % (self.user.get_full_name(), self.name_surfix)
return "%s" % self.user.get_full_name()
class Meta:
# Rename permissions
permissions = (
('can_see_participant', ugettext_noop("Can see participant")),
('can_manage_participant', ugettext_noop("Can manage participant")),
)
class DjangoGroup(models.Model, UserMixin):
user_prefix = 'djangogroup'
class OpenSlidesGroup(models.Model, PersonMixin):
person_prefix = 'openslides_group'
group = models.OneToOneField(Group)
group_as_person = models.BooleanField(default=False)
def __unicode__(self):
return unicode(self.group)
class DjangoUser(User, UserMixin):
user_prefix = 'djangouser'
def has_no_profile(self):
# TODO: Make ths with a Manager, so it does manipulate the sql query
return not hasattr(self, 'profile')
class Meta:
proxy = True
class ParticipantUsers(object):
def __init__(self, user_prefix=None, id=None):
self.user_prefix = user_prefix
class OpenSlidesUsersConnecter(object):
def __init__(self, person_prefix=None, id=None):
self.person_prefix = person_prefix
self.id = id
def __iter__(self):
if not self.user_prefix or self.user_prefix == Profile.user_prefix:
if not self.person_prefix or self.person_prefix == OpenSlidesUser.person_prefix:
if self.id:
yield Profile.objects.get(pk=self.id)
yield OpenSlidesUser.objects.get(pk=self.id)
else:
for profile in Profile.objects.all():
yield profile
for user in OpenSlidesUser.objects.all():
yield user
if not self.user_prefix or self.user_prefix == DjangoGroup.user_prefix:
if not self.person_prefix or self.person_prefix == OpenSlidesGroup.person_prefix:
if self.id:
yield DjangoGroup.objects.get(pk=self.id)
yield OpenSlidesObject.objects.get(pk=self.id)
else:
for group in DjangoGroup.objects.all():
for group in OpenSlidesGroup.objects.all():
yield group
if not self.user_prefix or self.user_prefix == DjangoUser.user_prefix:
if self.id:
yield DjangoUser.objects.get(pk=self.id)
else:
for user in DjangoUser.objects.all():
if user.has_no_profile():
yield user
elif self.user_prefix:
# If only users where requested, return the profile object.
yield user.profile
def __getitem__(self, key):
return Profile.objects.get(pk=key)
return OpenSlidesUser.objects.get(pk=key)
@receiver(receiv_users, dispatch_uid="participant_profile")
def receiv_users(sender, **kwargs):
return ParticipantUsers(user_prefix=kwargs['user_prefix'], id=kwargs['id'])
@receiver(receiv_persons, dispatch_uid="participant")
def receiv_persons(sender, **kwargs):
return OpenSlidesUsersConnecter(person_prefix=kwargs['person_prefix'], id=kwargs['id'])
@receiver(default_config_value, dispatch_uid="participant_default_config")
@ -153,8 +133,15 @@ def default_config(sender, key, **kwargs):
"""
Default values for the participant app.
"""
# TODO: Rename config-vars
return {
'participant_pdf_system_url': 'http://example.com:8000',
'participant_pdf_welcometext': _('Welcome to OpenSlides!'),
'admin_password': None,
}.get(key)
@receiver(signals.post_save, sender=User)
def user_post_save(sender, instance, signal, *args, **kwargs):
# Creates OpenSlidesUser
profile, new = OpenSlidesUser.objects.get_or_create(user=instance)

View File

@ -46,10 +46,10 @@ from openslides.utils.views import FormView, PDFView
from openslides.config.models import config
from openslides.participant.models import Profile, DjangoGroup
from openslides.participant.models import OpenSlidesUser, OpenSlidesGroup
from openslides.participant.api import gen_username, gen_password
from openslides.participant.forms import (UserNewForm, UserEditForm,
ProfileForm, UsersettingsForm, UserImportForm, GroupForm,
OpenSlidesUserForm, UsersettingsForm, UserImportForm, GroupForm,
AdminPasswordChangeForm, ConfigForm)
@ -78,53 +78,55 @@ def get_overview(request):
query = User.objects
if 'gender' in sortfilter:
query = query.filter(profile__gender__iexact=sortfilter['gender'][0])
query = query.filter(openslidesuser__gender__iexact=sortfilter['gender'][0])
if 'group' in sortfilter:
query = query.filter(profile__group__iexact=sortfilter['group'][0])
query = query.filter(openslidesuser__group__iexact=sortfilter['name_surfix'][0])
if 'type' in sortfilter:
query = query.filter(profile__type__iexact=sortfilter['type'][0])
query = query.filter(openslidesuser__type__iexact=sortfilter['type'][0])
if 'committee' in sortfilter:
query = query. \
filter(profile__committee__iexact=sortfilter['committee'][0])
filter(openslidesuser__committee__iexact=sortfilter['committee'][0])
if 'status' in sortfilter:
query = query.filter(is_active=sortfilter['status'][0])
if 'sort' in sortfilter:
if sortfilter['sort'][0] in ['first_name', 'last_name', 'last_login']:
query = query.order_by(sortfilter['sort'][0])
elif sortfilter['sort'][0] in ['group', 'type', 'committee', 'comment']:
query = query.order_by('profile__%s' % sortfilter['sort'][0])
elif sortfilter['sort'][0] in ['name_surfix', 'type', 'committee', 'comment']:
query = query.order_by('openslidesuser__%s' % sortfilter['sort'][0])
else:
query = query.order_by('last_name')
if 'reverse' in sortfilter:
query = query.reverse()
# list of filtered users (with profile)
# list of filtered users
userlist = query.all()
users = []
for user in userlist:
try:
user.get_profile()
users.append(user)
except Profile.DoesNotExist:
user.openslidesuser
except OpenSlidesUser.DoesNotExist:
pass
# list of all existing users (with profile)
else:
users.append(user)
# list of all existing users
allusers = []
for user in User.objects.all():
try:
user.get_profile()
allusers.append(user)
except Profile.DoesNotExist:
user.openslidesuser
except OpenSlidesUser.DoesNotExist:
pass
else:
allusers.append(user)
# quotient of selected users and all users
if len(allusers) > 0:
percent = float(len(users)) * 100 / float(len(allusers))
else:
percent = 0
# list of all existing groups
groups = [p['group'] for p in Profile.objects.values('group') \
.exclude(group='').distinct()]
groups = [p['name_surfix'] for p in OpenSlidesUser.objects.values('name_surfix') \
.exclude(name_surfix='').distinct()]
# list of all existing committees
committees = [p['committee'] for p in Profile.objects.values('committee') \
committees = [p['committee'] for p in OpenSlidesUser.objects.values('committee') \
.exclude(committee='').distinct()]
return {
'users': users,
@ -142,7 +144,7 @@ def get_overview(request):
@template('participant/edit.html')
def edit(request, user_id=None):
"""
View to create and edit users with profile.
View to create and edit users.
"""
if user_id is not None:
user = User.objects.get(id=user_id)
@ -151,26 +153,31 @@ def edit(request, user_id=None):
if request.method == 'POST':
if user_id is None:
userform = UserNewForm(request.POST, prefix="user")
profileform = ProfileForm(request.POST, prefix="profile")
user_form = UserNewForm(request.POST, prefix="user")
openslides_user_form = OpenSlidesUserForm(request.POST, prefix="openslidesuser")
else:
userform = UserEditForm(request.POST, instance=user, prefix="user")
profileform = ProfileForm(request.POST, instance=user.profile,
prefix="profile")
user_form = UserEditForm(request.POST, instance=user, prefix="user")
openslides_user_form = OpenSlidesUserForm(request.POST, instance=user.openslidesuser,
prefix="openslidesuser")
if userform.is_valid() and profileform.is_valid():
user = userform.save()
if user_form.is_valid() and openslides_user_form.is_valid():
user = user_form.save(commit=False)
if user_id is None:
# TODO: call first_name and last_name though openslides_user
user.username = gen_username(user.first_name, user.last_name)
user.save()
profile = profileform.save(commit=False)
profile.user = user
openslides_user = user.openslidesuser
openslides_user_form = OpenSlidesUserForm(request.POST, instance=openslides_user, prefix="openslidesuser")
openslides_user_form.is_valid()
openslides_user = openslides_user_form.save(commit=False)
openslides_user.user = user
if user_id is None:
if not profile.firstpassword:
profile.firstpassword = gen_password()
profile.user.set_password(profile.firstpassword)
profile.user.save()
profile.save()
if not openslides_user.firstpassword:
openslides_user.firstpassword = gen_password()
openslides_user.user.set_password(openslides_user.firstpassword)
# TODO: Try not to save the user object
openslides_user.user.save()
openslides_user.save()
if user_id is None:
messages.success(request,
_('New participant was successfully created.'))
@ -185,15 +192,15 @@ def edit(request, user_id=None):
messages.error(request, _('Please check the form for errors.'))
else:
if user_id is None:
userform = UserNewForm(prefix="user")
profileform = ProfileForm(prefix="profile")
user_form = UserNewForm(prefix="user")
openslides_user_form = OpenSlidesUserForm(prefix="openslidesuser")
else:
userform = UserEditForm(instance=user, prefix="user")
profileform = ProfileForm(instance=user.profile, prefix="profile")
user_form = UserEditForm(instance=user, prefix="user")
openslides_user_form = OpenSlidesUserForm(instance=user.openslidesuser, prefix="openslidesuser")
# TODO: rename template vars
return {
'userform': userform,
'profileform': profileform,
'userform': user_form,
'profileform': openslides_user_form,
'edituser': user,
}
@ -330,7 +337,7 @@ def group_edit(request, group_id=None):
else:
messages.error(request, _('Please check the form for errors.'))
else:
if group and DjangoGroup.objects.filter(group=group).exists():
if group and OpenSlidesGroup.objects.filter(group=group).exists():
initial = {'as_user': True}
else:
initial = {'as_user': False}

View File

@ -0,0 +1,22 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
openslides.utils.person
~~~~~~~~~~~~~~~~~~~~~~~
Person api for OpenSlides
:copyright: 2011, 2012 by OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
from openslides.utils.person.signals import receiv_persons
from openslides.utils.person.api import generate_person_id, get_person, Persons
from openslides.utils.person.forms import PersonFormField, MultiplePersonFormField
from openslides.utils.person.models import PersonField, PersonMixin
class EmtyPerson(PersonMixin):
@property
def person_id(self):
return 'emtyuser'

View File

@ -0,0 +1,64 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
openslides.utils.person.api
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Usefull functions for the OpenSlides person api.
:copyright: 2011, 2012 by OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
from openslides.utils.person.signals import receiv_persons
class Persons(object):
"""
A Storage for a multiplicity of different Person-Objects.
"""
def __init__(self, person_prefix=None, id=None):
self.person_prefix = person_prefix
self.id = id
def __iter__(self):
try:
return iter(self._cache)
except AttributeError:
return iter(self.iter_persons())
def __len__(self):
return len(list(self.__iter__()))
def __getitem__(self, key):
return list(self)[key]
def iter_persons(self):
self._cache = list()
for receiver, persons in receiv_persons.send(
sender='persons', person_prefix=self.person_prefix, id=self.id):
for person in persons:
self._cache.append(person)
yield person
def generate_person_id(prefix, id):
if ':' in prefix:
raise ValueError("':' is not allowed in a the 'person_prefix'")
return "%s:%d" % (prefix, id)
def split_person_id(person_id):
data = person_id.split(':', 1)
if len(data) == 2 and data[0] and data[1]:
return data
raise TypeError("Invalid person_id: '%s'" % person_id)
def get_person(person_id):
try:
person_prefix, id = split_person_id(person_id)
except TypeError:
from openslides.utils.person import EmtyPerson
return EmtyPerson()
return Persons(person_prefix=person_prefix, id=id)[0]

View File

@ -1,10 +1,10 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
openslides.utils.user.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~
openslides.utils.person.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Forms and FormFields for the OpenSlides user api.
Forms and FormFields for the OpenSlides person api.
:copyright: 2011, 2012 by OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
@ -12,21 +12,21 @@
from django import forms
from openslides.utils.user.api import Users, get_user
from openslides.utils.person.api import Persons, get_person
class UserChoices(object):
class PersonChoices(object):
def __init__(self, field):
self.field = field
def __iter__(self):
if self.field.empty_label is not None:
yield (u"", self.field.empty_label)
for user in Users():
yield (user.uid, user)
for person in Persons():
yield (person.person_id, person)
class UserFormField(forms.fields.ChoiceField):
class PersonFormField(forms.fields.ChoiceField):
def __init__(self, required=True, initial=None, empty_label=u"---------",
*args, **kwargs):
if required and (initial is not None):
@ -46,32 +46,32 @@ class UserFormField(forms.fields.ChoiceField):
# the property self.choices. In this case, just return self._choices.
if hasattr(self, '_choices'):
return self._choices
return UserChoices(self)
return PersonChoices(self)
choices = property(_get_choices, forms.fields.ChoiceField._set_choices)
def to_python(self, value):
return get_user(value)
return get_person(value)
def valid_value(self, value):
return super(UserFormField, self).valid_value(value.uid)
return super(PersonFormField, self).valid_value(value.person_id)
class MultipleUserFormField(UserFormField):
class MultiplePersonFormField(PersonFormField):
widget = forms.widgets.SelectMultiple
def __init__(self, *args, **kwargs):
super(MultipleUserFormField, self).__init__(empty_label=None,
super(MultiplePersonFormField, self).__init__(empty_label=None,
*args, **kwargs)
def to_python(self, value):
if hasattr(value, '__iter__'):
return [super(MultipleUserFormField, self).to_python(v)
return [super(MultiplePersonFormField, self).to_python(v)
for v in value]
return super(MultipleUserFormField, self).to_python(value)
return super(MultiplePersonFormField, self).to_python(value)
def valid_value(self, value):
if hasattr(value, '__iter__'):
return [super(MultipleUserFormField, self).valid_value(v)
return [super(MultiplePersonFormField, self).valid_value(v)
for v in value]
return super(MultipleUserFormField, self).valid_value(value)
return super(MultiplePersonFormField, self).valid_value(value)

View File

@ -1,25 +1,25 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
openslides.utils.user.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
openslides.utils.person.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Models and ModelFields for the OpenSlides user api.
Models and ModelFields for the OpenSlides person api.
:copyright: 2011, 2012 by OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
from django.db import models
from openslides.utils.user.forms import UserFormField
from openslides.utils.user.api import get_user, generate_uid
from openslides.utils.person.forms import PersonFormField
from openslides.utils.person.api import get_person, generate_person_id
class UserField(models.fields.Field):
class PersonField(models.fields.Field):
__metaclass__ = models.SubfieldBase
def __init__(self, *args, **kwargs):
super(UserField, self).__init__(max_length=255, *args, **kwargs)
super(PersonField, self).__init__(max_length=255, *args, **kwargs)
# TODO: Validate the uid
def get_internal_type(self):
@ -29,36 +29,36 @@ class UserField(models.fields.Field):
"""
Convert string value to a User Object.
"""
if hasattr(value, 'uid'):
user = value
if hasattr(value, 'person_id'):
person = value
else:
user = get_user(value)
person = get_person(value)
user.prepare_database_save = (
lambda unused: UserField().get_prep_value(user))
return user
person.prepare_database_save = (
lambda unused: PersonField().get_prep_value(person))
return person
def get_prep_value(self, value):
return value.uid
return value.person_id
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.get_prep_value(value)
def formfield(self, **kwargs):
defaults = {'form_class': UserFormField}
defaults = {'form_class': PersonFormField}
defaults.update(kwargs)
return super(UserField, self).formfield(**defaults)
return super(PersonField, self).formfield(**defaults)
class UserMixin(object):
class PersonMixin(object):
@property
def uid(self):
def person_id(self):
try:
return generate_uid(self.user_prefix, self.pk)
return generate_person_id(self.person_prefix, self.pk)
except AttributeError:
raise AttributeError("%s has to have a attribute 'user_prefix'"
% self)
def __repr__(self):
return 'User: %s' % self.uid
return 'Person: %s' % self.person_id

View File

@ -12,4 +12,4 @@
from django.dispatch import Signal
receiv_users = Signal(providing_args=['user_prefix', 'id'])
receiv_persons = Signal(providing_args=['person_prefix', 'id'])

View File

@ -1,22 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
openslides.utils.user
~~~~~~~~~~~~~~~~~~~~~
User api for OpenSlides
:copyright: 2011, 2012 by OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
from openslides.utils.user.signals import receiv_users
from openslides.utils.user.api import generate_uid, split_uid, get_user, Users
from openslides.utils.user.forms import UserFormField, MultipleUserFormField
from openslides.utils.user.models import UserField, UserMixin
class EmtyUser(UserMixin):
@property
def uid(self):
return 'emtyuser'

View File

@ -1,65 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
openslides.utils.user.api
~~~~~~~~~~~~~~~~~~~~~~~~~
Usefull functions for the OpenSlides user api.
:copyright: 2011, 2012 by OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
from openslides.utils.user.signals import receiv_users
class Users(object):
"""
A Storage for a multiplicity of different User-Objects.
"""
def __init__(self, user_prefix=None, id=None):
self.user_prefix = user_prefix
self.id = id
def __iter__(self):
try:
return iter(self._cache)
except AttributeError:
return iter(self.iter_users())
def __len__(self):
return len(list(self.__iter__()))
def __getitem__(self, key):
user_list = list(self)
return user_list[key]
def iter_users(self):
self._cache = list()
for receiver, users in receiv_users.send(
sender='users', user_prefix=self.user_prefix, id=self.id):
for user in users:
self._cache.append(user)
yield user
def generate_uid(prefix, id):
if ':' in prefix:
raise ValueError("':' is not allowed in a the 'user_prefix'")
return "%s:%d" % (prefix, id)
def split_uid(uid):
data = uid.split(':', 1)
if len(data) == 2 and data[0] and data[1]:
return data
raise TypeError("Invalid uid: '%s'" % uid)
def get_user(uid):
try:
user_prefix, id = split_uid(uid)
except TypeError:
from openslides.utils.user import EmtyUser
return EmtyUser()
return Users(user_prefix=user_prefix, id=id)[0]