[Answer]-Django Url Not Finding Model

1👍

Two things:

  1. Reverse for 'reward' with arguments '()' and keyword arguments '{'slug': u'yummy-cake'}' not found → in your get_absolute_url method, you tell Django to look for an url pattern named reward which is not in your urlconf. Change it to prize and it should work.

  2. “if I manually type the url, I get page not found” → Your pattern is \w+, which is described in the documentation as

When the LOCALE and UNICODE flags are not specified, matches any
alphanumeric character and the underscore; this is equivalent to the
set [a-zA-Z0-9_]. With LOCALE, it will match the set [0-9_] plus
whatever characters are defined as alphanumeric for the current
locale. If UNICODE is set, this will match the characters [0-9_] plus
whatever is classified as alphanumeric in the Unicode character
properties database.

so it only matches letters, numbers and the underscore. It does not match the ‘-‘ in ‘yummy-cake’. You can try this in a python shell:

    import re
    pat = re.compile(r'^prizes/(?P<slug>\w+)/$')
    pat.match("prizes/yummy-cake/")  # no match returned
    pat.match("prizes/yummycake/")  # → <_sre.SRE_Match object at 0x7f852c3244e0>
    pat = re.compile(r'^prizes/(?P<slug>[-\w]+)/$')  # lets fix the pattern
    pat.match("prizes/yummy-cake/")  # now it works → <_sre.SRE_Match object at 0x7f852c3244e0>
👤sk1p

Leave a comment