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

时间:2017-02-19 12:55:52

标签: python django reactjs django-rest-framework

我正在尝试向我的数据库添加评论,但收到错误'OrderedDict' object has no attribute 'pk'

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

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);
    });

}

我的serializers.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

我的views.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

发送邮件请求时,它会通过正常的方式发送。如果我删除其中一个字段,则返回400。现在我得到了这个500 [Internal server] error

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
     

这里 - > 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

1 个答案:

答案 0 :(得分:1)

我认为这仅仅是因为您的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中已提及:

  

需要一种方法来确定应将哪些视图用于   超链接到模型实例。

     

默认情况下,超链接应与以下视图名称相对应:   匹配样式'{model_name} -detail',并按以下方式查找实例   一个pk关键字参数。

因此HyperlinkedModelSerializer试图找到一个视图,该视图应用于链接到Post对象,但找不到该视图。高度怀疑帖子的网址为空id