python - AttributeError:“PostDetailView”对象没有属性“方法”
问题描述
我尝试在我的代码中使用 dispatch() 但不幸遇到了多个我无法解决的错误。最后一个错误是 AttributeError: 'PostDetailView' object has no attribute 'method'。我无法显示现有评论(我通过管理页面添加了一些评论)或评论表单。
视图.py
class PostDetailView(DetailView):
model = Post
def dispatch(request, *args, **kwargs):
post = get_object_or_404(Post)
comments = post.comments.filter(active=True)
new_comment = None
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.post = post
new_comment.save()
else:
comment_form = CommentForm()
return render(request, template_name, {'post': post,
'comments': comments,
'new_comment': new_comment,
'comment_form': comment_form})
表格.py
from .models import Comment
from django import forms
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('name', 'email', 'body')
模型.py
class Post(models.Model):
title = models.CharField(max_length=20)
content = models.TextField()
date_posted = models.DateTimeField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk':self.pk})
class Comment(models.Model):
post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=False)
解决方案
添加为方法定义中self
的第一个位置参数(之前request
) 。dispatch
传递给的第一个参数dispatch()
是视图对象,您称之为request
. 这就是为什么当你这样做时request.method
它正在寻找method
视图对象上的属性。
推荐阅读
- node.js - 如何检测应用程序是否从 dmg 文件运行?
- powerbi - 如何在 Power BI 中获得几年总销售额的百分比?
- python-3.x - 将文本文件中的数值数组转换为 numpy 数组的最佳方法是什么?
- intellij-idea - IntelliJ junit5 运行配置 - 使用标签运行所有测试,并在特定包中运行
- r - R OMPR 包 - 限制选择的唯一变量组件的数量
- excel - 如何根据 Excel 工作表中输入的选项过滤表格?
- java - 如果对象名称不在列表中,Java ArrayList 将类对象添加到列表中?
- python - 正确获取 django 模型
- javascript - 而不是点击,我想用滚动/new.php 打开页面
- javascript - 如何将此代码转换为异步等待语法?(反应原生)