Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django HttpResponseRedirect() doesn't work – it doesn't redirect to the page

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading