首页 > 解决方案 > 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)

标签: pythonpython-3.xdjango-formsdjango-templatesdjango-views

解决方案


添加为方法定义中self的第一个位置参数(之前request) 。dispatch

传递给的第一个参数dispatch()是视图对象,您称之为request. 这就是为什么当你这样做时request.method它正在寻找method视图对象上的属性。


推荐阅读