删除评论后,返回帖子/ <slug:pk_slug> /

时间:2020-05-06 00:34:10

标签: python django python-3.x django-views

我可以删除评论52(请参见下面的屏幕截图)。然后,我的困难是将用户带回到页面localhost:8000 / post / 8 /。当我找出问题的答案时,我目前正在使用return render(request, 'blog/home.html')作为临时解决方案。我已经包含了views.py的代码,在大多数代码行的前面都有一个井号(#)。这代表了我多次失败的尝试。

views.py

def delete_own_comment(request, pk):

  #template_name = 'post_detail.html'

  comment = get_object_or_404(Comment, id=pk)

  #comments = Comment.objects.filter(post=post.id ,active=True)
  #comment_form=CommentForm()
  #post = Post.objects.filter(id=8).first()
  comment.delete()

  return render(request, 'blog/home.html')

  #return HttpResponseRedirect(reverse('post_detail', kwargs={'pk_slug':comment.post}))


  #return redirect('post_detail', pk=comment.post.id)
  #return render(request, template_name, {'comment_form': comment_form})

#'comments': comments,

urls.py

    path('post/<slug:pk_slug>/', views.post_detail, name='post-detail'),

models.py

# Create your models here.
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)
    url = models.SlugField(max_length=500, blank=True)

def save(self, *args, **kwargs):
    self.url= slugify(self.title)
    super().save(*args, **kwargs)

def __str__(self):
    return self.title 

def get_absolute_url(self):
    #return reverse('article_detail', kwargs={'slug': self.slug})
    return reverse('post-detail', kwargs={'pk_slug': self.slug})


class Comment(models.Model):

#The foriegn key is linked to the ID field in the Post model
#id = models.IntegerField(primary_key=True, blank=False)
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(default = timezone.now())
active = models.BooleanField(default=True)
url= models.SlugField(max_length=500, blank=True)
#id = models.AutoField(primary_key=True)

class Meta:
    ordering = ['created_on']

def __str__(self):
    return 'Comment {} by {}'.format(self.body, self.name)

def save(self, *args, **kwargs):
    self.url= slugify(self.post)
    super().save(*args, **kwargs)

def get_absolute_url(self):
    return reverse('article_detail', kwargs={'slug': self.slug})

enter image description here

更新

我尝试了return reverse('post_detail', kwargs={'pk_slug':comment.post.id}),并收到以下错误消息。

enter image description here

更新2

我将其从post_detail更改为post-detail

enter image description here

1 个答案:

答案 0 :(得分:1)

首次导入:

from django.shortcuts import redirect

然后将其添加为return语句:

return redirect('post-detail', comment.post.id)

comment.post.id将获取与要删除的评论相关的Post对象的实际ID。