简体   繁体   English

AttributeError: 'PostDetailView' 对象没有属性 'method

[英]AttributeError: 'PostDetailView' object has no attribute 'method

I tried using dispatch() in my code but unfortunately ran into multiple errors I could not resolve.我尝试在我的代码中使用 dispatch() 但不幸的是遇到了多个我无法解决的错误。 The last error was AttributeError: 'PostDetailView' object has no attribute 'method'.最后一个错误是 AttributeError: 'PostDetailView' object has no attribute 'method'。 I can't get existing comments to appear (I added some via the admin page) or the comment form.我无法显示现有评论(我通过管理页面添加了一些评论)或评论表单。

views.py视图.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表格.py

from .models import Comment
from django import forms

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('name', 'email', 'body')

models.py模型.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)

Add self as the first positional argument (before request ) in your dispatch method definition.添加self作为dispatch方法定义中的第一个位置参数(在request之前)。

The first argument passed to dispatch() is the view object, which you call request .传递给dispatch()的第一个参数是视图对象,您称之为request That's why when you do request.method it's looking for the method attribute on the view object.这就是为什么当您执行request.method它会在视图对象上寻找method属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM