OpenSlides/openslides/utils/person/models.py

81 lines
2.5 KiB
Python
Raw Normal View History

2012-08-04 13:18:06 +02:00
# -*- coding: utf-8 -*-
from django.contrib.auth.models import AnonymousUser
from django.db import models
2012-08-04 13:18:06 +02:00
from openslides.utils.exceptions import OpenSlidesError
from .api import generate_person_id, get_person
2013-02-02 21:19:37 +01:00
from .forms import PersonFormField
2012-08-04 13:18:06 +02:00
class PersonField(models.fields.Field):
2012-08-04 14:47:09 +02:00
__metaclass__ = models.SubfieldBase
2012-08-04 13:18:06 +02:00
2012-08-04 14:47:09 +02:00
def __init__(self, *args, **kwargs):
2013-02-02 21:19:37 +01:00
kwargs['max_length'] = 255
super(PersonField, self).__init__(*args, **kwargs)
2012-08-04 13:18:06 +02:00
2012-08-04 14:47:09 +02:00
def get_internal_type(self):
return "CharField"
2012-08-04 13:18:06 +02:00
def to_python(self, value):
2012-08-04 14:47:09 +02:00
"""
Convert an object to an user Object.
'value' has to be an object derivated from PersonMixin, None or has to
have an attribute 'person_id'.
2012-08-04 14:47:09 +02:00
"""
2013-03-14 22:18:56 +01:00
if isinstance(value, PersonMixin):
2013-02-02 21:19:37 +01:00
return value
elif value is None:
return None
elif isinstance(value, AnonymousUser):
raise AttributeError('An AnonymousUser can not be saved into the database.')
2012-08-04 14:47:09 +02:00
else:
try:
return get_person(value)
except AttributeError:
raise AttributeError('You can not save \'%s\' into a person field.'
% type(value))
2012-08-04 13:18:06 +02:00
2012-08-04 14:47:09 +02:00
def get_prep_value(self, value):
2013-02-02 21:19:37 +01:00
"""
Convert a person object to a string, to store it in the database.
"""
if value is None:
# For Fields with null=True
2013-02-02 21:19:37 +01:00
return None
2013-03-18 12:34:47 +01:00
elif isinstance(value, basestring):
# The object is already a a person_id
2013-03-18 12:34:47 +01:00
return value
elif hasattr(value, 'person_id'):
# The object is a person
2013-02-02 21:19:37 +01:00
return value.person_id
else:
OpenSlidesError('%s (%s) is no person' % (value, type(value)))
2012-08-04 13:18:06 +02:00
2012-08-04 14:47:09 +02:00
def formfield(self, **kwargs):
defaults = {'form_class': PersonFormField}
2012-08-04 14:47:09 +02:00
defaults.update(kwargs)
return super(PersonField, self).formfield(**defaults)
2012-08-04 13:18:06 +02:00
class PersonMixin(object):
2012-08-04 14:47:09 +02:00
@property
def person_id(self):
2012-08-04 14:47:09 +02:00
try:
return generate_person_id(self.person_prefix, self.pk)
2012-08-04 14:47:09 +02:00
except AttributeError:
raise AttributeError("%s has to have a attribute 'person_prefix'"
2012-08-04 14:47:09 +02:00
% self)
2013-03-14 22:18:56 +01:00
def __unicode__(self):
return self.person_id
2013-03-14 22:18:56 +01:00
def prepare_database_save(self, field):
if type(field) is PersonField:
return self.person_id
else:
return super(PersonMixin, self).prepare_database_save(field)