How to do custom fields on init from serializers?

5,558 views
Skip to first unread message

Johnny W. Santos

unread,
Jan 14, 2013, 8:20:19 AM1/14/13
to django-res...@googlegroups.com
I want to make fields with custom behaviors just like in django forms. Can i do that with serializers to?

I tried this just to create a field like on forms:

def __init__(self, *args, **kwargs):
    self.fields['pdf'] = serializers.FileField()

but returns:
AttributeError at /edicoes/nova/
'EdicaoSerializer' object has no attribute 'fields'

Where can i found some documentation about this?

--
Johnny W. dos Santos
  

Tom Christie

unread,
Jan 14, 2013, 8:53:16 AM1/14/13
to django-res...@googlegroups.com
> I tried this just to create a field like on forms:

Call the superclass __init__ first.  That'll work.

> Where can i found some documentation about this?

You won't.  I'd probably consider this a private API, at least for now.

Johnny W. Santos

unread,
Jan 14, 2013, 12:27:05 PM1/14/13
to django-res...@googlegroups.com
I did this, but the pdf field don't show in form.

class EdicaoSerializer(serializers.HyperlinkedModelSerializer):
    
    class Meta:
        model = Edicao
        exclude = ('data_file', 'zip')
        
    def __init__(self, *args, **kwargs):
        super(EdicaoSerializer, self).__init__(*args, **kwargs)
        self.fields['pdf'] = serializers.FileField()


2013/1/14 Tom Christie <t...@tomchristie.com>

Johnny W. Santos

unread,
Jan 15, 2013, 6:36:03 AM1/15/13
to django-res...@googlegroups.com
Anyone have a guess?

2013/1/14 Johnny W. Santos <johnny....@gmail.com>

Tom Christie

unread,
Jan 15, 2013, 7:11:17 AM1/15/13
to django-res...@googlegroups.com
Okay, I got the impression you wanted to dynamically add fields to your serializer for some reason.
What you're looking for  is doing pretty much that same thing you would do with a ModelForm.

    class EdicaoSerializer(serializers.HyperlinkedModelSerializer):
        pdf = serializers.FileField()

        class Meta:
            model = Edicao
            exclude = ('data_file', 'zip')

Reply all
Reply to author
Forward
Message has been deleted
0 new messages