对象没有属性得到,而覆盖POST方法

问题描述:

class CreatePosts(CreateView): 
    model = posts 
    fields = ['title','comments'] 

    def post(self, request, *args, **kwargs): 

     current_inspectionfile = Inspectionfile.objects.get(pk = self.kwargs['pk']) 
     new_post = posts.objects.create(inspectionfile=current_inspectionfile, 
       title =request.POST.get("title"), 
       comments =request.POST.get("comments")) 

     return new_post 

模型对象没有属性得到,而覆盖POST方法

class posts(models.Model): 
    inspectionfile = models.ForeignKey(Inspectionfile, on_delete=models.CASCADE, default=1) 
    title = models.CharField(max_length=120) 
    comments = models.TextField() 
    flag = models.BooleanField(default=False) 

    def get_absolute_url(self): 
     return reverse('posts_form', kwargs={'pk': self.pk}) 

    def __str__(self): 
     return self.title 

形式是一个简单的模板:

<form class = "form_horizontal" action = "" method = "post"> 
    {% csrf_token %} 
    {{form.as_p}} 
    <button type="submit">Submit</button> 
    </form> 


my url is: 
url(r'^(?P<pk>[0-9]+)/$',views.CreatePosts.as_view(),name=='posts_form') 

我得到的错误是

“帖子“对象没有属性获取。

我试过看到其他博客,但似乎没有任何工作。我已经重写了CreatePosts类中的post方法以某种方式工作。这就是为什么我得到这个错误,或者是因为一些URL不匹配。一旦用户点击提交,我希望他们回到相同的形式,因此URL。

+1

为什么你是否重写'post'?你应该在'form_valid'中做这个逻辑。 –

你的POST方法返回模型的实例

return new_post 

所有意见必须返回一个HttpResponse对象,以便与上下文中的新的工作岗位,返回最简单的事情将是render

return render(request, self.template_name, {'new_post': new_post })