我想知道有人可以帮助我并为我澄清这个错误。
我正在做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'
有人可以澄清这个错误,并帮助我克服这一点。
答案 0 :(得分:3)
使用widget
属性定义表单字段类型:
code = serializers.CharField(widget=forms.Textarea())
您可能正在使用DRF v2.x.x,它不支持style
类中的Field
参数