Reputation: 2641
I was wondering can someone help me and clarify this error for me.
I am doing the Django REST Framework Tutorial, and I got to the part when I am creating a Serializer class.
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
Now mine problem is this, when I go in to the shell to serialize and when I want to import
from snippets.serializers import SnippetSerializer
the module throw this error:
>>> 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'
Can someone please clarify this error and help me overcome this.
Upvotes: 2
Views: 1371
Reputation: 15484
Use widget
attribute do define form field type:
code = serializers.CharField(widget=forms.Textarea())
You're probably using DRF v2.x.x, which doesn't support style
argument in Field
class
Upvotes: 3