2015-09-26 86 views
2

這是我所定義的模型:模型對象有沒有屬性保存

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' 

我在做什麼錯了?

+0

真的,你應該使用的ModelForm。然後,您可以使用CreateView並擺脫這裏的大部分邏輯。 –

回答

4

您的視圖類和模型類具有相同的名稱,即Post

所以,當你在你看來做Post(user=..),它試圖創建Post視圖對象,然後調用它的.save()而它應該已經創建了Post模型對象,並將其保存。

要解決您的問題,您需要將您的視圖類名稱更改爲其他名稱。

嘗試改變

class Post(View): 

喜歡的東西

class PostView(View): 
2

您有複製的對象,名稱爲Post,它們混合在一起。看起來您正在嘗試保存View對象而不是Model對象。

相關問題