gpt4 book ai didi

python - Django REST框架教程1中的类型错误: Serialization

转载 作者:行者123 更新时间:2023-11-30 23:17:41 24 4
gpt4 key购买 nike

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

我正在做 Django REST Framework 教程,当我创建 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'

有人可以澄清这个错误并帮助我克服这个问题吗?

最佳答案

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

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

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

关于python - Django REST框架教程1中的类型错误: Serialization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27222568/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com