python - 发表评论后如何重定向我的用户
问题描述
所以我刚刚学会了如何在我的博客上添加评论。现在的问题是我无法将我的用户重定向到相关的博客文章。这真的很令人沮丧,因为我在 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)
解决方案
您可以在这里使用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],因为给定的输入本身是无效的,并且表单可以进行正确的验证,以及删除大量样板代码。
推荐阅读
- coq - 假设并证明关于不同类型相等性的定理(证明具有依赖类型的两个偶数之和的交换性)
- sql - 按地址相似但经纬度不同的 SQL 分组
- typescript - 如何在没有冗余的情况下配置 TypeScript 别名?
- c++ - 在不丢弃限定符的情况下正确转发 lambda 中的参数包
- javascript - 在 React 中保留子元素的同时禁用父元素上的触摸操作
- c# - 使用 Moq 在 UnitTest 中获取调用方法的返回值
- python - 我的播放器移动不正确,按住键时,它应该连续移动,但只移动一次
- python - Python 中带有 Stem 和 CherryPy 的洋葱服务器
- postgresql - 如何使用 PostgreSQL 在分层任务树中找到平均进度(每级)?
- java - Maven 构建过程在没有任何错误的情况下终止