gpt4 book ai didi

python - 需要字段的 django rest 框架错误

转载 作者:行者123 更新时间:2023-12-05 09:16:59 25 4
gpt4 key购买 nike

我一直在关注 http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/ 上的教程(这非常好)但我已经到了最后,我正在运行命令

http -a admin:password123 POST http://127.0.0.1:8000/snippets/代码="打印789"

它给了我一个错误:

HTTP/1.1 400 Bad Request Allow: GET, POST, HEAD, OPTIONS Content-Length: 37 Content-Type: application/json Date: Wed, 28 Feb 2018 18:29:15 GMT Server: WSGIServer/0.2 CPython/3.6.3 Vary: Accept, Cookie X-Frame-Options: SAMEORIGIN

{ "owner": [ "This field is required." ] }

所有者字段在可浏览的 api 上也可见,为我创建的所有用户提供选项。虽然保存它时(浏览器或命令行)它确实保存了发出请求的用户,因此该部分是正确的。我认为它不应该在可浏览的 api 上可见,并且在 api 调用中不需要,因为它从请求中计算出来。

这是我的代码:

views.py:

class SnippetList(generics.ListCreateAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

def perform_create(self, serializer):
serializer.save(owner=self.request.user)

模型.py:

class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='')
code = models.TextField()
linenos = models.BooleanField(default=False)
language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
owner = models.ForeignKey('auth.User', related_name='snippets', on_delete=models.CASCADE)
highlighted = models.TextField()

class Meta:
ordering = ('created',)

def save(self, *args, **kwargs):
lexer = get_lexer_by_name(self.language)
linenos = self.linenos and 'table' or False
options = self.title and {'title': self.title} or {}
formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options)
self.highlighted = highlight(self.code, lexer, formatter)
super(Snippet, self).save(*args, **kwargs)

序列化器.py

class SnippetSerializer(serializers.ModelSerializer):
class Meta:
model = Snippet
fields = ('id', 'title', 'code', 'linenos', 'language', 'style', 'owner')
owner = serializers.ReadOnlyField(source='owner.username')

最佳答案

在序列化器中,您将字段定义为类的属性,而不是在 Meta 中。试试这个:

class SnippetSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Snippet
fields = ('id', 'title', 'code', 'linenos', 'language', 'style', 'owner')

关于python - 需要字段的 django rest 框架错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49045839/

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