OpenSlides/openslides/utils/person/models.py

71 lines
1.9 KiB
Python
Raw Normal View History

2012-08-04 13:18:06 +02:00
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
openslides.utils.person.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2012-08-04 13:18:06 +02:00
Models and ModelFields for the OpenSlides person api.
2012-08-04 13:18:06 +02:00
:copyright: 2011, 2012 by OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
2012-08-04 14:47:09 +02:00
from django.db import models
2012-08-04 13:18:06 +02:00
2013-02-02 21:19:37 +01:00
from .forms import PersonFormField
2013-03-14 22:18:56 +01:00
from .api import get_person, generate_person_id
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 string value to a User Object.
"""
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
2012-08-04 14:47:09 +02:00
else:
2013-02-02 21:19:37 +01:00
return get_person(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:
return None
else:
return value.person_id
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 'MyPerson: %s' % self.person_id
def prepare_database_save(self, field):
if type(field) is PersonField:
return self.person_id
else:
return super(PersonMixin, self).prepare_database_save(field)