django-orchestra/orchestra/api/serializers.py

112 lines
4.4 KiB
Python
Raw Normal View History

2015-04-23 19:46:23 +00:00
import copy
2015-10-05 13:31:08 +00:00
from django.core.exceptions import ValidationError
2015-05-18 15:21:42 +00:00
from django.db import models
2014-05-08 16:59:35 +00:00
from django.forms import widgets
2015-04-04 17:44:07 +00:00
from django.utils.translation import ugettext_lazy as _
2014-05-08 16:59:35 +00:00
from rest_framework import serializers
2015-04-23 19:46:23 +00:00
from rest_framework.utils import model_meta
2014-05-08 16:59:35 +00:00
from ..core.validators import validate_password
class SetPasswordSerializer(serializers.Serializer):
password = serializers.CharField(max_length=128, label=_('Password'),
2015-04-23 14:34:04 +00:00
style={'widget': widgets.PasswordInput}, validators=[validate_password])
2014-05-08 16:59:35 +00:00
class HyperlinkedModelSerializer(serializers.HyperlinkedModelSerializer):
""" support for postonly_fields, fields whose value can only be set on post """
2014-10-15 21:18:50 +00:00
2015-04-23 14:34:04 +00:00
def validate(self, attrs):
""" calls model.clean() """
attrs = super(HyperlinkedModelSerializer, self).validate(attrs)
2015-05-18 15:21:42 +00:00
if isinstance(attrs, models.Model):
return attrs
2015-04-23 19:46:23 +00:00
validated_data = dict(attrs)
ModelClass = self.Meta.model
# Remove many-to-many relationships from validated_data.
info = model_meta.get_field_info(ModelClass)
for field_name, relation_info in info.relations.items():
if relation_info.to_many and (field_name in validated_data):
validated_data.pop(field_name)
if self.instance:
# on update: Merge provided fields with instance field
instance = copy.deepcopy(self.instance)
for key, value in validated_data.items():
setattr(instance, key, value)
else:
instance = ModelClass(**validated_data)
2015-04-23 14:34:04 +00:00
instance.clean()
return attrs
2015-04-23 19:46:23 +00:00
def post_only_cleanning(self, instance, validated_data):
""" removes postonly_fields from attrs """
2015-04-23 14:34:04 +00:00
model_attrs = dict(**validated_data)
2015-05-18 15:21:42 +00:00
post_only_fields = getattr(self, 'post_only_fields', None)
if instance is not None and post_only_fields:
2015-04-23 14:34:04 +00:00
for attr, value in validated_data.items():
2015-05-18 15:21:42 +00:00
if attr in post_only_fields:
model_attrs.pop(attr)
2015-04-23 19:46:23 +00:00
return model_attrs
def update(self, instance, validated_data):
""" removes postonly_fields from attrs when not posting """
model_attrs = self.post_only_cleanning(instance, validated_data)
2015-04-23 14:34:04 +00:00
return super(HyperlinkedModelSerializer, self).update(instance, model_attrs)
2015-04-23 19:46:23 +00:00
def partial_update(self, instance, validated_data):
""" removes postonly_fields from attrs when not posting """
model_attrs = self.post_only_cleanning(instance, validated_data)
return super(HyperlinkedModelSerializer, self).partial_update(instance, model_attrs)
2014-10-15 21:18:50 +00:00
2015-05-18 15:21:42 +00:00
class RelatedHyperlinkedModelSerializer(HyperlinkedModelSerializer):
""" returns object on to_internal_value based on URL """
def to_internal_value(self, data):
url = data.get('url')
if not url:
raise ValidationError({
'url': "URL is required."
})
account = self.get_account()
2015-10-05 13:31:08 +00:00
queryset = self.Meta.model.objects.filter(account=account)
2015-05-18 15:21:42 +00:00
self.fields['url'].queryset = queryset
obj = self.fields['url'].to_internal_value(url)
return obj
2015-04-23 14:34:04 +00:00
class SetPasswordHyperlinkedSerializer(HyperlinkedModelSerializer):
password = serializers.CharField(max_length=128, label=_('Password'),
validators=[validate_password], write_only=True, required=False,
style={'widget': widgets.PasswordInput})
def validate_password(self, attrs, source):
""" POST only password """
if self.instance:
if 'password' in attrs:
raise serializers.ValidationError(_("Can not set password"))
elif 'password' not in attrs:
raise serializers.ValidationError(_("Password required"))
return attrs
2014-05-08 16:59:35 +00:00
2015-04-23 14:34:04 +00:00
def validate(self, attrs):
""" remove password in case is not a real model field """
try:
2016-04-30 11:23:13 +00:00
self.Meta.model._meta.get_field('password')
2015-04-23 14:34:04 +00:00
except models.FieldDoesNotExist:
pass
else:
password = attrs.pop('password', None)
attrs = super().validate(attrs)
2015-04-23 14:34:04 +00:00
if password is not None:
attrs['password'] = password
return attrs
2014-05-08 16:59:35 +00:00
2015-04-23 14:34:04 +00:00
def create(self, validated_data):
password = validated_data.pop('password')
instance = self.Meta.model(**validated_data)
instance.set_password(password)
instance.save()
return instance