[Python] Django HTTPResponseRedirect not redirecting to the url but rather adding the integer...

Discussão em 'Python' iniciado por Stack, Maio 5, 2025.

  1. Stack

    Stack Membro Participativo

    This is my view.py file

    from django.http import HttpResponse, HttpResponseRedirect, HttpResponseNotFound, Http404, HttpResponsePermanentRedirect
    from django.urls import reverse
    from django.shortcuts import render

    articles = {
    'sports': 'sports page',
    'finance' : 'finance page',
    'tech' : 'tech page',
    }

    def home_view(request):
    return HttpResponse("My App Home Page")

    def news_view(request, topic):
    try:
    result = articles[topic]
    return HttpResponse(result)
    except:
    raise Http404("404 Generic view error")


    def mul_view(request,num1,num2):
    num_result = num1 * num2
    result = f"{num1} * {num2} = {num_result}"
    return HttpResponse(str(result))

    def num_page_view(request, num_page):
    topic_list = list(articles.keys())
    topic = topic_list[num_page]
    return HttpResponseRedirect(topic)


    and this is my url file of the app

    from django.urls import path
    from . import views

    urlpatterns = [
    path('<int:num_page>/', views.num_page_view, name='num_page'),
    # path('', views.home_view, name='home'),
    path('<topic>/', views.news_view, name='topic-page'),
    path('<int:num1>/<int:num2>/', views.mul_view, name='multiply'),
    ]


    What's happening here is a bit hard to explain for me as English is not my first language, but here is my best effort.

    I have created a function num_page_view that takes a number as a parameter and has a list of all keys of articles dictionary then the number is provided to the list as an index and stored into a variable topic that is then send as the output in the HttpResponseRedirect.

    Then I added a a new path that takes links to the num_page_view but instead of redirecting it to the topic it rather concatenates the integer to the url with the topic

    For eg.

    my_app/1/

    should return my_app/finance but instead it concatenates that number to the url and makes it my_app/1/finance, even though I am using HttpResponseRedirect which logically should return the given url name that I am providing it through the topic variable

    Continue reading...

Compartilhe esta Página