所以我刚刚学会了如何在我的博客上添加评论。现在的问题是我无法将我的用户重定向到相关的博客文章。这真的很令人沮丧,因为我在互联网上看到很多人谈论 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 <b>reverse</b>
class Annonce(models.Model):
# ...
def <b>get_absolute_url</b>(self):
return reverse('annonce_detail', kwargs={'pk': self.pk})
这里 annonce_detail
是假设 View 的名称,因此在您的 urls.py
中,我们有一个如下路径:
# app/urls.py
from django.urls import path
from app import views
urlpatterns = [
path('annonce/<int:pk>', views.annonce_detail, name=<b>'annonce_detail'</b>),
# ...
]
这意味着对于给定的 Annonce
对象,我们可以询问 some_annonce.get_absolute_url()
,它会返回类似 /annonce/123
.
现在redirect
[Django-doc]考虑带有 get_absolute_url
的模型对象。事实上,正如文档所说:
Returns an
HttpResponseRedirect
to the appropriate URL for the arguments passed.The arguments could be:
- A model: the model's
get_absolute_url()
function will be called.- A view name, possibly with arguments:
reverse()
will be used to reverse-resolve the name.- An absolute or relative URL, which will be used as-is for the redirect location.
By default issues a temporary redirect; pass
permanent=True
to issue a permanent redirect.
如果您在该模型上定义了这样的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 <b>redirect(annonce)</b>
context = {
"annonce": annonce,
"comments": comments,
}
return render(request, "annonces/annonce.html", context)
Note: models typically have singular names, so
Comment
, notComments
.
Note: you might want to consider working with forms [Django-doc] since the given input is not per se valid, and a form can do proper validation, as well as removing a lot of boilerplate code.
关于python - 如何在发表评论后重定向我的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56317490/