Django HttpResponseRedirect работает некорректно
Я пытаюсь перенаправить с помощью HttpResponseRedirect, и в учебнике на YT учитель набрал url так:
return HttpResponseRedirect("challenge/" + month_list[month-1])
поэтому url "http://localhost:8000/challenge/1" изменился на "http://localhost:8000/challenge/january".
Когда я пытаюсь сделать это, мой url меняется на "http://localhost:8000/challenge/challenge/january", снова повторяя "вызов".
views.py
from django.shortcuts import render
from django.http import HttpResponse,HttpResponseNotFound,HttpResponseRedirect
from django.urls import reverse
# Create your views here.
months_challenges = {
"january" : "desafio janeiro",
"february" : "desafio february",
"march" : "desafio march",
"april" : "desafio april",
"may" : "desafio may",
"june" : "desafio june",
"july" : "desafio july",
"august" : "desafio august",
"september" : "desafio september",
"october" : "desafio october",
"november" : "desafio november",
"december" : "desafio december",
}
def month_challenge_num(request,month):
month_list = list(months_challenges.keys())
if(month>len(month_list)):
return HttpResponseNotFound("Não achamos")
else:
return HttpResponseRedirect("challenge/" + month_list[month-1])
def month_challenge(request,month):
try:
return HttpResponse(months_challenges[month])
except:
return HttpResponseNotFound("Não achamos str")
urls.py приложения
from django.urls import path
from . import views
urlpatterns = [
path("<int:month>",views.month_challenge_num),
path("<str:month>",views.month_challenge)
]
urls.py проекта
"""monthly_challenges URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path("challenge/", include("challenges.urls"), name="challenges")
]
Я думаю, что ошибка происходит из-за включения в urls.py проекта, но я не знаю. Я хочу продолжать использовать этот include, но я хочу использовать функцию redirect для перенаправления на другую страницу, которая не включена в "challenges area"
Вам нужно работать с абсолютным путем, поэтому с ведущей косой чертой:
def month_challenge_num(request,month):
month_list = list(months_challenges)
if month > len(month_list):
return HttpResponseNotFound("Não achamos")
else:
return HttpResponseRedirect(f'/challenge/{month_list[month-1]}')
Однако удобнее работать с именованным представлением:
from django.urls import path
from . import views
app_name = 'challenge'
urlpatterns = [
path('<int:month>/', views.month_challenge_num),
path('<str:month>/', views.month_challenge, name='month')
]
и перенаправить с помощью:
from django.shortcuts import redirect
def month_challenge_num(request,month):
month_list = list(months_challenges)
if month > len(month_list):
return HttpResponseNotFound("Não achamos")
else:
return redirect('challenge:month', month_list[month-1])