我尝试在代码中使用dispatch(),但不幸遇到了多个无法解决的错误。最后一个错误是AttributeError:“ PostDetailView”对象没有属性“ method”。我无法显示现有评论(我通过管理页面添加了一些评论)或评论表单。
views.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})
forms.py
from .models import Comment
from django import forms
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('name', 'email', 'body')
models.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)
答案 0 :(得分:0)
在您的 self
方法定义中添加 request
作为第一个位置参数(在 dispatch
之前)。
传递给 dispatch()
的第一个参数是视图对象,您称之为 request
。这就是为什么当您执行 request.method
时,它会在视图对象上寻找 method
属性。