OpenSlides/openslides/utils/person/models.py

65 lines
1.8 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
from openslides.utils.person.forms import PersonFormField
from openslides.utils.person.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):
super(PersonField, self).__init__(max_length=255, *args, **kwargs)
2012-08-04 14:47:09 +02:00
# TODO: Validate the uid
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.
"""
if hasattr(value, 'person_id'):
person = value
2012-08-04 14:47:09 +02:00
else:
person = get_person(value)
2012-08-04 13:18:06 +02:00
person.prepare_database_save = (
lambda unused: PersonField().get_prep_value(person))
return person
2012-08-04 13:18:06 +02:00
2012-08-04 14:47:09 +02:00
def get_prep_value(self, value):
return value.person_id
2012-08-04 13:18:06 +02:00
2012-08-04 14:47:09 +02:00
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.get_prep_value(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 'user_prefix'"
% self)
def __repr__(self):
return 'Person: %s' % self.person_id