模型对象没有属性保存

时间:2015-09-26 12:15:40

标签: python django django-models django-views

这是我定义的模型:

class Post(models.Model):
    user = models.ForeignKey(MSUser)
    upvote_count = models.IntegerField()
    post_status = models.IntegerField(choices = POST_STATUS)
    title = models.CharField(max_length=200,null = True,blank = True)
    content = models.CharField(max_length=1000,null = False,blank = False)
    created_at = models.DateTimeField(auto_now_add=True, null=True)
    updated_at = models.DateTimeField(auto_now=True, null=True)

    def __unicode__(self):
        return self.content

    def get_user(self):
        return self.user.__unicode__()

    def save(self, **kwargs):
        super(Post, self).save(**kwargs)

以下是观点:

class Post (View):
    @method_decorator(csrf_exempt) # To be removed
    def dispatch(self, request, *args, **kwargs):
#         Placeholder for fine grained permission system to prevent unwarranted GET/POST/PUTS
#          Check request.user properties (like group etc) and request.method 
#             return HttpResponseForbidden()
        return super(Post, self).dispatch(request, *args, **kwargs)

    def get(request):
        pass

    def post(self, request):
        responseMessage = {}  
        user = request.user
        if user.is_authenticated():
            title = request.POST.get('title', None)
            content = request.POST.get('content', None)
            if title is None or content is None:
                responseMessage['status'] = 'failure'
                responseMessage['message'] = 'Mandatory data is missing.'
                return HttpResponse(json.dumps(responseMessage))
            else:
                newPost = Post(user = user,
                               title = title,
                               content = content,
                               post_status = PS_CREATED,
                               upvote_count = 0)
                newPost.save()
                responseMessage['status'] = 'success'
                responseMessage['message'] = 'Post created successfully'
                responseMessage['server_id'] = newPost.id
                return HttpResponse(json.dumps(responseMessage))

Postman发送请求时,我不断收到以下错误:

AttributeError: 'Post' object has no attribute 'save'

我做错了什么?

2 个答案:

答案 0 :(得分:4)

您的视图类和模型类具有相同的名称,即Post

因此,当您在视图中执行Post(user=..)时,它会尝试创建Post视图对象,然后在其上调用.save(),而它应创建Post模型对象并保存它。

要解决您的问题,您需要将视图类名更改为其他名称。

尝试更改

class Post(View): 

类似

class PostView(View): 

答案 1 :(得分:2)

您有混合的名为Post的重复对象。看起来您正在尝试保存View对象而不是Model对象。