Search code examples
htmldjango-viewsweb-applicationsdjango-urls

Error fetching the entry page through Django url path


I'm trying to solve a problem in CS50W Project 1 'wiki'. I'm working on the specification - 'Entry Page' where if I add /wiki/title to url it should fetch the entry page. These are my files:

wiki/urls.py

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include("encyclopedia.urls"))
]

encyclopedia/urls.py

from django.urls import path

from . import views

# List of urls
urlpatterns = [
    path("", views.index, name="index"),
    path("<str:title>", views.entry, name="page"),
]

encyclopedia/views.py

def entry(request, title):
    """
    A function that retrieves the content of an entry based on the title provided.
    If the entry is not found, it renders a 404 error page.
    """
    content = util.get_entry(title)

    if content == None:
        return render(request, "encyclopedia/404.html")
    else:
        html_content = markdown2.markdown(content)
        return render(request, "encyclopedia/entry.html", {
            "title": title, "content": html_content
        })

entry.html file:

{% extends "encyclopedia/layout.html" %}

{% block title %}
    {{ title | safe }}
{% endblock %}

{% block body %}    
    {{ content | safe }}
    <!--Link to edit page-->
    <div>
        <a href="{% url 'edit' title %}" class="btn btn-primary mt-5">
        Edit Page
        </a>
    </div>    
{% endblock %}

This is the error I'm getting when I add 'css' to the url:

Page not found (404)
Request Method: GET
Request URL:    http://localhost:8000/css/
Using the URLconf defined in wiki.urls, Django tried these URL patterns, in this order:

admin/
[name='index']
<str:title> [name='page']
search/ [name='search']
newpage/ [name='newpage']
edit/<str:title> [name='edit']
random/ [name='random']
The current path, css/, didn’t match any of these.

With any other entries (eg - django/html etc.) added I'm just getting "encyclopedia/404.html".

But when the url input exactly matches the name of entry file (eg- 'CSS - CSS', 'Git - Git') it gives me the correct entry page and any other combination of upper & lower case letters raising the errors above.

I tried different paths in the urls.py. Also tried different variations of the code in def entry(#, #) to get the contents of entries. Appreciate the help!


Solution

  • It häppens because you are don't close you url path with '/', and, by default, django.middleware.common.CommonMiddleware is switched on.

    In your case:

    #encyclopedia/urls.py    
    from django.urls import path    
    from . import views
    
    # List of urls
    urlpatterns = [
        path("", views.index, name="index"),
        path("<str:title>/", views.entry, name="page"),
    ]