2012-08-04 13:18:06 +02:00
|
|
|
#!/usr/bin/env python
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
"""
|
2012-08-04 14:47:09 +02:00
|
|
|
openslides.utils.user.models
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
2012-08-04 13:18:06 +02:00
|
|
|
|
2012-08-04 14:47:09 +02:00
|
|
|
Models and ModelFields for the OpenSlides user 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
|
|
|
|
2012-08-04 14:47:09 +02:00
|
|
|
from openslides.utils.user.forms import UserFormField
|
|
|
|
from openslides.utils.user.api import get_user, generate_uid
|
2012-08-04 13:18:06 +02:00
|
|
|
|
|
|
|
|
2012-08-04 14:47:09 +02:00
|
|
|
class UserField(models.fields.Field):
|
|
|
|
__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(UserField, self).__init__(max_length=255, *args, **kwargs)
|
|
|
|
# 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, 'uid'):
|
|
|
|
user = value
|
|
|
|
else:
|
|
|
|
user = get_user(value)
|
2012-08-04 13:18:06 +02:00
|
|
|
|
2012-08-04 14:47:09 +02:00
|
|
|
user.prepare_database_save = (
|
|
|
|
lambda unused: UserField().get_prep_value(user))
|
|
|
|
return user
|
2012-08-04 13:18:06 +02:00
|
|
|
|
2012-08-04 14:47:09 +02:00
|
|
|
def get_prep_value(self, value):
|
|
|
|
return value.uid
|
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': UserFormField}
|
|
|
|
defaults.update(kwargs)
|
|
|
|
return super(UserField, self).formfield(**defaults)
|
2012-08-04 13:18:06 +02:00
|
|
|
|
|
|
|
|
2012-08-04 14:47:09 +02:00
|
|
|
class UserMixin(object):
|
|
|
|
@property
|
|
|
|
def uid(self):
|
|
|
|
try:
|
|
|
|
return generate_uid(self.user_prefix, self.pk)
|
|
|
|
except AttributeError:
|
|
|
|
raise AttributeError("%s has to have a attribute 'user_prefix'"
|
|
|
|
% self)
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return 'User: %s' % self.uid
|