django-orchestra-test/orchestra/apps/mails/serializers.py

50 lines
1.9 KiB
Python
Raw Normal View History

2014-08-22 15:31:44 +00:00
from rest_framework import serializers
from orchestra.apps.accounts.serializers import AccountSerializerMixin
from .models import Mailbox, Address
class MailboxSerializer(AccountSerializerMixin, serializers.HyperlinkedModelSerializer):
class Meta:
model = Mailbox
2014-10-06 14:57:02 +00:00
# TODO 'use_custom_filtering',
2014-10-07 13:08:59 +00:00
fields = ('url', 'name', 'password', 'custom_filtering', 'addresses', 'is_active')
2014-10-06 14:57:02 +00:00
def validate_password(self, attrs, source):
""" POST only password """
if self.object:
if 'password' in attrs:
raise serializers.ValidationError(_("Can not set password"))
elif 'password' not in attrs:
raise serializers.ValidationError(_("Password required"))
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(MailboxSerializer, self).save_object(obj, **kwargs)
2014-08-22 15:31:44 +00:00
class AddressSerializer(AccountSerializerMixin, serializers.HyperlinkedModelSerializer):
class Meta:
model = Address
fields = ('url', 'name', 'domain', 'mailboxes', 'forward')
def get_fields(self, *args, **kwargs):
fields = super(AddressSerializer, self).get_fields(*args, **kwargs)
2014-09-30 16:39:47 +00:00
account = self.context['view'].request.user.pk
2014-08-22 15:31:44 +00:00
mailboxes = fields['mailboxes'].queryset
fields['mailboxes'].queryset = mailboxes.filter(account=account)
# TODO do it on permissions or in self.filter_by_account_field ?
domain = fields['domain'].queryset
2014-09-30 16:39:47 +00:00
fields['domain'].queryset = domain.filter(account=account)
2014-08-22 15:31:44 +00:00
return fields
2014-10-06 14:57:02 +00:00
def validate(self, attrs):
if not attrs['mailboxes'] and not attrs['forward']:
2014-10-07 13:08:59 +00:00
raise serializers.ValidationError("mailboxes or forward addresses should be provided")
2014-10-06 14:57:02 +00:00
return attrs