2014-05-08 16:59:35 +00:00
|
|
|
from django.forms import widgets
|
|
|
|
from django.utils.translation import ugettext, ugettext_lazy as _
|
|
|
|
from rest_framework import serializers
|
|
|
|
|
|
|
|
from orchestra.apps.accounts.serializers import AccountSerializerMixin
|
|
|
|
from orchestra.core.validators import validate_password
|
|
|
|
|
2014-10-14 13:50:19 +00:00
|
|
|
from .models import Database, DatabaseUser
|
2014-05-08 16:59:35 +00:00
|
|
|
|
|
|
|
|
2014-10-14 13:50:19 +00:00
|
|
|
class RelatedDatabaseUserSerializer(serializers.HyperlinkedModelSerializer):
|
2014-05-08 16:59:35 +00:00
|
|
|
class Meta:
|
2014-10-14 13:50:19 +00:00
|
|
|
model = DatabaseUser
|
|
|
|
fields = ('url', 'username')
|
|
|
|
|
|
|
|
def from_native(self, data, files=None):
|
|
|
|
return DatabaseUser.objects.get(username=data['username'])
|
2014-05-08 16:59:35 +00:00
|
|
|
|
|
|
|
|
2014-10-14 13:50:19 +00:00
|
|
|
class DatabaseSerializer(AccountSerializerMixin, serializers.HyperlinkedModelSerializer):
|
|
|
|
users = RelatedDatabaseUserSerializer(many=True, allow_add_remove=True)
|
|
|
|
|
2014-05-08 16:59:35 +00:00
|
|
|
class Meta:
|
2014-10-14 13:50:19 +00:00
|
|
|
model = Database
|
|
|
|
fields = ('url', 'name', 'type', 'users')
|
2014-05-08 16:59:35 +00:00
|
|
|
|
|
|
|
|
2014-10-14 13:50:19 +00:00
|
|
|
class RelatedDatabaseSerializer(serializers.HyperlinkedModelSerializer):
|
2014-05-08 16:59:35 +00:00
|
|
|
class Meta:
|
|
|
|
model = Database
|
2014-10-14 13:50:19 +00:00
|
|
|
fields = ('url', 'name',)
|
|
|
|
|
|
|
|
def from_native(self, data, files=None):
|
|
|
|
return Database.objects.get(name=data['name'])
|
2014-05-08 16:59:35 +00:00
|
|
|
|
|
|
|
|
|
|
|
class DatabaseUserSerializer(AccountSerializerMixin, serializers.HyperlinkedModelSerializer):
|
|
|
|
password = serializers.CharField(max_length=128, label=_('Password'),
|
|
|
|
validators=[validate_password], write_only=True,
|
|
|
|
widget=widgets.PasswordInput)
|
2014-10-14 13:50:19 +00:00
|
|
|
databases = RelatedDatabaseSerializer(many=True, allow_add_remove=True, required=False)
|
2014-05-08 16:59:35 +00:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
model = DatabaseUser
|
2014-10-14 13:50:19 +00:00
|
|
|
fields = ('url', 'username', 'password', 'type', 'databases')
|
|
|
|
|
|
|
|
def save_object(self, obj, **kwargs):
|
|
|
|
# FIXME this method will be called when saving nested serializers :(
|
|
|
|
if not obj.pk:
|
|
|
|
obj.set_password(obj.password)
|
|
|
|
super(DatabaseUserSerializer, self).save_object(obj, **kwargs)
|