我一直在关注 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')
https://stackoverflow.com/questions/49045839/
相关文章:
python - "invalid character ' u ' looking for begi
android-studio - "APK was defined multiple times",
regex - 如何在Hive SQL中选择具有相同前缀(开始)或后缀(结束)或中间关键字(包括)的
google-cloud-platform - 在 Google Cloud Storage 上恢复
javafx - 如何在 JavaFX 中设置默认关闭操作?
r - Shiny :在 numericInput 中右键单击时提供上下文菜单?