JohnJ
JohnJ

Reputation: 7056

404 on a simple template view - strange

I have a django app set up consisting of ListViews, TemplateViews etc.. So, I just added a small templateview to it like so:

#views.py
class TermsTemplateView(TemplateView):
    template_name = "terms.html"

#urls.py
url(r'^terms/$', TermsTemplateView.as_view(), name='terms'),

and in terms.html, I am using for linking:

<a href="{% url 'terms' %}">Terms & Conditions</a>

For some strange reason, I keep getting 404 on localhost/terms as follows:

404: No <model_name> found matching the query

I am baffled why this is happening all of a sudden. I have the same set up for "about", "thanks", "contact" pages, and they seem to display it with no problems.

..and the worst part is, if I modify the urls.py like so:

url(r'^/terms/$', TermsTemplateView.as_view(), name='terms'),

and then go to http://127.0.0.1:8000//terms/ - the page seems to be there.. I am surprised why this is so :(

Any help would enlighten me!

Upvotes: 1

Views: 289

Answers (1)

alecxe
alecxe

Reputation: 474001

The / at the end is the culprit of your problems. localhost/terms doesn't match '^terms/$' regular expression, localhost/terms/ does.

You can make / at the end optional by using ?:

url(r'^terms/?$', TermsTemplateView.as_view(), name='terms'),

UPD: Note that there is a better solution to the problem, APPEND_SLASH:

When set to True, if the request URL does not match any of the patterns in the URLconf and it doesn’t end in a slash, an HTTP redirect is issued to the same URL with a slash appended.

Also see:

Upvotes: 1

Related Questions