首页 > 解决方案 > 发表评论后如何重定向我的用户

问题描述

所以我刚刚学会了如何在我的博客上添加评论。现在的问题是我无法将我的用户重定向到相关的博客文章。这真的很令人沮丧,因为我在 Internet 上看到很多人都在谈论 get_absolute_url,这让我很困惑。

from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Annonce, Comments
from django.shortcuts import get_object_or_404
from django.core.paginator import Paginator

def annonceView(request, annonce_id):
    annonce = get_object_or_404(Annonce, pk=annonce_id)
    comments = Comments.objects.filter(auteur=annonce_id)
    if request.method == "POST":
        content = request.POST["add_comment"]
        if content:
        new_comment = Comments.objects.create(content=content, auteur=annonce)
        new_comment.save()
        return redirect(annonce)

    context = {
        "annonce": annonce,
        "comments": comments,
    }

    return render(request, "annonces/annonce.html", context)

标签: pythondjangoblogs

解决方案


您可以在这里使用get_absolute_url[Django-doc]是正确的。您可以将此类方法添加到模型中,例如:

# app/models.py

from django.db import models
from django.urls import reverse

class Annonce(models.Model):

    # ...

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

annonce_detail是一个假设视图的名称,因此在您的 中urls.py,我们有如下路径:

# app/urls.py

from django.urls import path
from app import views

urlpatterns = [
    path('annonce/<int:pk>', views.annonce_detail, name='annonce_detail'),
    # ...
]

这意味着对于给定的Annonce对象,我们可以询问some_annonce.get_absolute_url(),它会以类似的方式响应/annonce/123

现在redirect[Django-doc]将模型对象get_absolute_url考虑在内。确实,正如文档所述:

为传递的参数返回HttpResponseRedirect适当的 URL。

论据可能是:

  • 模型:模型get_absolute_url()函数将被调用。
  • 视图名称,可能带有参数:reverse()将用于反向解析名称。
  • 绝对或相对 URL,将按原样用于重定向位置。

默认情况下发出临时重定向;通过permanent=True发出永久重定向。

如果您因此get_absolute_url在该模型上定义了此类,则可以将该对象传递给redirect,例如:

def annonceView(request, annonce_id):
    annonce = get_object_or_404(Annonce, pk=annonce_id)
    comments = Comments.objects.filter(auteur=annonce_id)
    if request.method == "POST":
        content = request.POST["add_comment"]
        if content:
        new_comment = Comments.objects.create(content=content, auteur=annonce)
        new_comment.save()
        return redirect(annonce)

    context = {
        "annonce": annonce,
        "comments": comments,
    }

    return render(request, "annonces/annonce.html", context)

注意:模型通常具有单数名称,因此Comment不是 Comments

 

注意:您可能需要考虑使用表单[Django-doc],因为给定的输入本身是无效的,并且表单可以进行正确的验证,以及删除大量样板代码。


推荐阅读