Issue
I am coding a Django project for a Wikipedia-like site (CS50W project 1). I have one app inside the project called encyclopedia. Inside my views.py
file for this app, I have a redirect, for which I use the django.urls.reverse()
function. The link to the documentation for this function can be found here.
Now for the problem: If the user visits /wiki/file
where file is not a valid page, then the markdown file will not be found in the entry
view. And, as you can see, it is supposed to redirect you to the not found page. However, the code return HttpResponseRedirect(reverse("notfound"))
loops the user back to the entry
view indefinitely, instead of the user being redirected to the not found page.
I have found two solutions so far: One can reorder the URL patterns so that the notfound pattern appears before the entry pattern, or a slash can be added to either of the aforementioned URL patterns.
I am, however, looking for the cause of the problem. I am currently considering the possibility that the reverse()
function is using the URL pattern instead of the name for some reason.
urls.py
file for encyclopedia:
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("wiki/<str:title>", views.entry, name="entry"),
path("wiki/notfound", views.notfound, name="notfound"),
]
views.py
file for encyclopedia:
from django.shortcuts import render
import markdown2
from django.urls import reverse
from django.http import HttpResponseRedirect
from . import util
def index(request):
return render(request, "encyclopedia/index.html", {
"entries": util.list_entries()
})
def entry(request, title):
md = util.get_entry(title)
if md is None:
return HttpResponseRedirect(reverse("notfound"))
else:
html = markdown2.markdown(md)
return render(request, "encyclopedia/entry.html", {
"title": title,
"entry": html
})
def notfound(request):
return render(request, "encyclopedia/notfound.html")
Solution
I have discovered the answer to my question. It is not a caveat in the implementation of reverse()
. It is merely an interesting outcome due to the way the code works. reverse()
finds the URL pattern with the name notfound and returns it as /wiki/notfound
. Then HttpResponseRedirect()
redirects the user to that URL, which just so happens to appear as a URL for the entry view first, redirecting the user back to the entry view and restarting the process. The not found page will never be reached, because its URL is a subset of the URLs for the entry view which is above it.
Answered By - Joseph Chemaly
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.