2016-11-15 53 views
0
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'中做這個邏輯。 –

回答

1

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

return new_post 

所有意見必須返回一個HttpResponse對象,以便與上下文中的新的工作崗位,返回最簡單的事情將是render

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