I was trying to implement the function listing(request, listId)
that when user wants to post a comment without login, it will be redirected to the login page.
This is the code of my listing(request, listId)
in 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
}
)
Here is the urls.py
, note that the name of login url is "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")
]
The problem is each time when I click the submit button without login, it doesn't redirect me to the login page but stays in the original page, which is not what I expect.
I also tried to replace HttpsResponseRedirect(reverse("login"))
with redirect("login")
and type the whole url in like HttpsResponseRedirect("/login")
. Both of them didn't work.
Thanks in advance for any help!
The issue here is that you're not returning the redirect. it should be:
return HttpResponseRedirect(...)
It now is still running the code to render the template, this is the only response django will see.