Django REST框架中的TypeError教程1:序列化

时间:2014-12-01 06:04:43

标签: python django serialization django-rest-framework

我想知道有人可以帮助我并为我澄清这个错误。

我正在做Django REST框架教程,当我创建一个Serializer类时,我接触到了这一部分。

from django.forms import widgets
from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES

class SnippetSerializer(serializers.ModelSerializer):
    pk = serializers.IntegerField(read_only=True)
    title = serializers.CharField(required=False,
                                  max_length=100)
    code = serializers.CharField(style={'type': 'textarea'})
    linenos = serializers.BooleanField(required=False)
    language = serializers.ChoiceField(choices=LANGUAGE_CHOICES,
                                       default='python')
    style = serializers.ChoiceField(choices=STYLE_CHOICES,
                                    default='friendly')

class Meta:
    model = Snippet
    fields = ('id', 'title', 'code', 'linenos', 'language', 'style')


def create(self, validated_attrs):
    """
    Create and return a new 'Snippet' instance, given the validated data.
    """
    return Snippet.objects.create(**validated_attrs)

def update(self, instance, validated_attrs):
    """
    Update and return an existing 'Snippet' instance, given the validated data.
    """
    instance.title = validated_attrs.get('title', instance.title)
    instance.code = validated_attrs.get('code', instance.code)
    instance.linenos = validated_attrs.get('linenos', instance.linenos)
    instance.language = validated_attrs.get('language', instance.language)
    instance.style = validated_attrs.get('style', instance.style)
    instance.save()
    return instance

现在我的问题就是这个,当我进入shell进行序列化和我想要导入时 from snippets.serializers import SnippetSerializer模块抛出此错误:

>>> from snippets.serializers import SnippetSerializer

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/petarp/Documents/Django_Rest_Framework/serialization_tutorial/tutorial/snippets/serializers.py", line 6, in <module>
    class SnippetSerializer(serializers.ModelSerializer):
  File "/home/petarp/Documents/Django_Rest_Framework/serialization_tutorial/tutorial/snippets/serializers.py", line 10, in SnippetSerializer
    code = serializers.CharField(style={'type': 'textarea'})
  File "/home/petarp/.virtualenvs/env/local/lib/python2.7/site-packages/rest_framework/fields.py", line 468, in __init__
    super(CharField, self).__init__(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'style'

有人可以澄清这个错误,并帮助我克服这一点。

1 个答案:

答案 0 :(得分:3)

使用widget属性定义表单字段类型:

code = serializers.CharField(widget=forms.Textarea())

您可能正在使用DRF v2.x.x,它不支持style类中的Field参数