在基于Django类的视图(DetailView)中与POST方法相反

时间:2019-12-28 12:47:06

标签: django redirect

我可能有一个琐碎的问题,但是我是Django的新手,我不知道为什么要重定向到这里时出现错误。我得到正确的url,但出现错误'str'对象没有属性'get'。我怎么了格式正确,并且在db中创建了对象。这只是关于错误的重定向。感谢您的帮助。

我的urls.py:

urlpatterns = [
    path('', PostListView.as_view(), name='blog-home'),
    path('user/<str:username>/', UserPostListView.as_view(), name='user-posts'),
    path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
    path('post/new/', PostCreateView.as_view(), name='post-create'),
    path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
    path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
    path('comments/delete/<int:pk>/', views.CommentDeleteView.as_view(), name='delete-comment'),
    path('about/', views.about, name='blog-about'),

]

views.py

class PostDetailView(DetailView):
    model = Post

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['comments'] = Comment.objects.all()[::-1]
        context['comm_form'] = CommentCreateForm()
        return context

    def post(self, request, *args, **kwargs):
        if request.method == 'POST':  
            comm_form = CommentCreateForm(request.POST)
            comm_form.instance.post = Post.objects.get(id=self.kwargs.get('pk'))
            comm_form.instance.author = self.request.user 
            comm_form.save()
            return reverse('post-detail', kwargs={'pk': self.kwargs.get('pk')})
        else:
            comm_form = CommentCreateForm()
            return reverse('post-detail', kwargs={'pk': self.kwargs.get('pk')})

models.py

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    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):
    comm_content = models.TextField(max_length=200)
    add_date = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)

    def __str__(self):
        return f"Comment of post {self.post} posted at {self.add_date}."

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.post.pk})

Error view

1 个答案:

答案 0 :(得分:1)

reverse(..) function [Django-doc]返回一个 string ,其中包含您重定向到的路径。但是视图需要返回HttpResponse,例如HttpResponseRedirect [Django-doc]

您可以利用redirect(..) function [Django-doc]来组合计算反向,并将结果包装在HttpResponse中。因此,您可以将代码修改为:

from django.shortcuts import redirect

class PostDetailView(DetailView):
    model = Post

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['comments'] = Comment.objects.all()[::-1]
        context['comm_form'] = CommentCreateForm()
        return context

    def post(self, request, *args, **kwargs):
        if request.method == 'POST':  
            comm_form = CommentCreateForm(request.POST)
            comm_form.instance.post = Post.objects.get(id=self.kwargs.get('pk'))
            comm_form.instance.author = self.request.user 
            comm_form.save()
            return redirect('post-detail', pk=self.kwargs.get('pk'))
        else:
            return redirect('post-detail', pk=self.kwargs.get('pk'))