django-orchestra/orchestra/apps/databases/serializers.py

70 lines
2.6 KiB
Python
Raw Normal View History

2014-05-08 16:59:35 +00:00
from django.forms import widgets
from django.utils.translation import ugettext, ugettext_lazy as _
from django.shortcuts import get_object_or_404
2014-05-08 16:59:35 +00:00
from rest_framework import serializers
2014-10-15 21:18:50 +00:00
from orchestra.api.serializers import HyperlinkedModelSerializer
2014-05-08 16:59:35 +00:00
from orchestra.apps.accounts.serializers import AccountSerializerMixin
from orchestra.core.validators import validate_password
from .models import Database, DatabaseUser
2014-05-08 16:59:35 +00:00
class RelatedDatabaseUserSerializer(AccountSerializerMixin, serializers.HyperlinkedModelSerializer):
2014-05-08 16:59:35 +00:00
class Meta:
model = DatabaseUser
fields = ('url', 'username')
def from_native(self, data, files=None):
queryset = self.opts.model.objects.filter(account=self.account)
return get_object_or_404(queryset, username=data['username'])
2014-05-08 16:59:35 +00:00
2014-10-15 21:18:50 +00:00
class DatabaseSerializer(AccountSerializerMixin, HyperlinkedModelSerializer):
users = RelatedDatabaseUserSerializer(many=True, allow_add_remove=True)
2014-05-08 16:59:35 +00:00
class Meta:
model = Database
fields = ('url', 'name', 'type', 'users')
2014-10-15 21:18:50 +00:00
postonly_fields = ('name', 'type')
def validate(self, attrs):
for user in attrs['users']:
if user.type != attrs['type']:
raise serializers.ValidationError("User type must be" % attrs['type'])
return attrs
2014-05-08 16:59:35 +00:00
class RelatedDatabaseSerializer(AccountSerializerMixin, serializers.HyperlinkedModelSerializer):
2014-05-08 16:59:35 +00:00
class Meta:
model = Database
fields = ('url', 'name',)
def from_native(self, data, files=None):
queryset = self.opts.model.objects.filter(account=self.account)
return get_object_or_404(queryset, name=data['name'])
2014-05-08 16:59:35 +00:00
2014-10-15 21:18:50 +00:00
class DatabaseUserSerializer(AccountSerializerMixin, HyperlinkedModelSerializer):
2014-05-08 16:59:35 +00:00
password = serializers.CharField(max_length=128, label=_('Password'),
validators=[validate_password], write_only=True,
widget=widgets.PasswordInput)
databases = RelatedDatabaseSerializer(many=True, allow_add_remove=True, required=False)
2014-10-15 21:18:50 +00:00
2014-05-08 16:59:35 +00:00
class Meta:
model = DatabaseUser
fields = ('url', 'username', 'password', 'type', 'databases')
2014-10-15 21:18:50 +00:00
postonly_fields = ('username', 'type')
def validate(self, attrs):
for database in attrs.get('databases', []):
if database.type != attrs['type']:
raise serializers.ValidationError("Database type must be" % attrs['type'])
return attrs
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)