OpenSlides/openslides/utils/person/models.py

65 lines
1.7 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
from .api import get_person, generate_person_id, Person
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-02-02 21:19:37 +01:00
if isinstance(value, Person):
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)
def __repr__(self):
return 'Person: %s' % self.person_id