gpt4 book ai didi

python - 如何使用 modelviewset 和 POST 请求创建对象?

转载 作者:太空狗 更新时间:2023-10-30 01:32:22 28 4
gpt4 key购买 nike

我试图向我的数据库添加评论,但出现错误 'OrderedDict' object has no attribute 'pk'

处理POST请求的react.js部分代码:

addComment() {
let url = this.props.post_url

axios.post('/api/comments/', {
post: url,
user: "http://127.0.0.1:8000/api/users/1/?format=json",
text: document.getElementsByName(url)[0].value,
csrfmiddlewaretoken: document.getElementsByName("csrfmiddlewaretoken")[0].value},
)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

}

我的序列化器.py:

from django.contrib.auth.models import User
from rest_framework import serializers

from .models import Post, Comment


class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'url')


class CommentSerializer(serializers.HyperlinkedModelSerializer):
#user = UserSerializer(many=False, required=False)
class Meta:
model = Comment
fields = ('id', "post", "user", 'text')
read_only_fields = ('id', "user")

def create(self):
user = None
request = self.context.get("request")
if request and hasattr(request, "user"):
user = request.user


class PostSerializer(serializers.HyperlinkedModelSerializer):
#user = UserSerializer(required=False)
comments = CommentSerializer(many=True, required=False, read_only=True)
class Meta:
model = Post
fields = ('id', 'title', "user", "url", "comments", 'text')
read_only_fields = ('id', "url", "comments")

def save(self):
user = None
request = self.context.get("request")
if request and hasattr(request, "user"):
user = request.user

我的观点.py

from django.contrib.auth.models import User
from api.serializers import UserSerializer
from rest_framework import viewsets

from .models import Comment, Post
from .serializers import CommentSerializer, PostSerializer


class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer


class CommentViewSet(viewsets.ModelViewSet):
queryset = Comment.objects.all()
serializer_class = CommentSerializer


class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer

当发送 Post-request 时,它会正常进行。如果我删除其中一个字段,它会返回 400。现在我收到此 500 [Internal server] 错误

AttributeError: 'OrderedDict' 对象没有属性 'pk'

错误似乎来自:

/home/halvor1606/.virtualenvs/django-react/local/lib/python2.7/site-packages/rest_framework/relations.py in get_url

   # Unsaved objects will not yet have a valid URL.

if hasattr(obj, 'pk') and obj.pk in (None, ''):

return None

Here-> lookup_value = getattr(obj, self.lookup_field) ...

   kwargs = {self.lookup_url_kwarg: lookup_value}

return self.reverse(view_name, kwargs=kwargs, request=request, format=format)

def get_name(self, obj):

return six.text_type(obj)

▶ 局部变量如下:-

Variable    Value

request <rest_framework.request.Request object at 0x7f4e59e75b90>

view_name 'post-detail'

obj OrderedDict([(u'title', u'adskjfj|'), (u'user', <User: halvor1606>), (u'text', u'kjkldsjf')])

self HyperlinkedIdentityField(read_only=True, view_name='post-detail')

format None

阅读其他有同样错误的问题。没有找到解决我问题的方法。

谢谢!

编辑:

通过将此添加到我的后序列化器中解决了这个问题:

def create(self, validated_data):
tmp_post = validated_data
user = None

request = self.context.get("request")
if request and hasattr(request, "user"):
user = request.user

post = Post.objects.create(
user=user,
title=tmp_post['title'],
text=tmp_post['text'],
)

return post

最佳答案

我认为这仅仅是因为你的 url 这里是空的:

addComment() {
let url = this.props.post_url

axios.post('/api/comments/', {
post: url,
user: "http://127.0.0.1:8000/api/users/1/?format=json",
text: document.getElementsByName(url)[0].value,
csrfmiddlewaretoken: document.getElementsByName("csrfmiddlewaretoken")[0].value},
)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}

由于您指定了 class CommentSerializer(serializers.HyperlinkedModelSerializer):,因此在 document 中提到了这一点:

There needs to be a way of determining which views should be used for hyperlinking to model instances.

By default hyperlinks are expected to correspond to a view name that matches the style '{model_name}-detail', and looks up the instance by a pk keyword argument.

所以 HyperlinkedModelSerializer 试图找到一个应该用于链接到 Post 对象的 View ,但找不到它。高度怀疑帖子 url 为空 id

关于python - 如何使用 modelviewset 和 POST 请求创建对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42327449/

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