覆盖 POST 方法时对象没有属性 get
object has no attribute get while overriding the POST method
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
型号
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')
我收到的错误是
"posts" object has no attribute get.
我试过查看其他博客,但似乎无济于事。我已经覆盖了 CreatePosts class 中的 post 方法以某种方式工作。这就是我收到此错误的原因,还是因为某些 URL 不匹配。一旦用户点击提交,我希望他们返回相同的表单,因此 URL.
您的 post 方法是 return 您模型的一个实例
return new_post
所有视图都必须 return 一个 HttpResponse,因此在上下文中使用新的 post return 最简单的事情是 render
return render(request, self.template_name, {'new_post': new_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
型号
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')
我收到的错误是
"posts" object has no attribute get.
我试过查看其他博客,但似乎无济于事。我已经覆盖了 CreatePosts class 中的 post 方法以某种方式工作。这就是我收到此错误的原因,还是因为某些 URL 不匹配。一旦用户点击提交,我希望他们返回相同的表单,因此 URL.
您的 post 方法是 return 您模型的一个实例
return new_post
所有视图都必须 return 一个 HttpResponse,因此在上下文中使用新的 post return 最简单的事情是 render
return render(request, self.template_name, {'new_post': new_post })