我正在尝试实现一个功能
listing(request, listId)
,当用户想在没有登录的情况下发表评论时,它将被重定向到登录页面。
这是我的
listing(request, listId)
在views.py
的代码
def listing(request, listId):
if request.method == "POST":
if request.user.is_authenticated:
# some code here to manipulate data
else:
HttpResponseRedirect(reverse("login"))
return render(request, "auctions/listing.html",
{
"listing":Listing.objects.get(pk=listId),
"comments": Listing.objects.get(pk=listId).itemComment.all(),
"bids": Listing.objects.get(pk=listId).itemBid.all(),
"bidCount": Listing.objects.get(pk=listId).itemBid.count(),
"currentPrice": currentPrice,
"isValidBid": True
}
)
这里是
urls.py
,注意登录网址的名称是"login"
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("add_listing", views.addListing, name="addListing"),
path("listing_<int:listId>", views.listing, name="listing")
]
问题是每次当我在没有登录的情况下单击提交按钮时,它不会将我重定向到登录页面而是停留在原始页面,这不是我所期望的。
我还尝试将
HttpsResponseRedirect(reverse("login"))
替换为 redirect("login")
并输入整个网址,如 HttpsResponseRedirect("/login")
。两个都没用。
预先感谢您的帮助!
这里的问题是您没有返回重定向。 应该是:
return HttpResponseRedirect(...)
现在仍在运行代码来渲染模板,这是 django 将看到的唯一响应。