Django Url Not Finding Model

104 Views Asked by At

I'm having trouble with my urlconf. I get the following error when trying to visit a page: NoReverseMatch at /admin/r/17/1/

Reverse for 'reward' with arguments '()' and keyword arguments '{'slug': u'yummy-cake'}' not found. 1 pattern(s) tried: ['prizes/(?P)/$']

And if I manually type the url, I get page not found.

My urlconf:

....
url(r'^prizes/$', PrizeList.as_view(), name="prize_list"),
url(r'^prizes/(?P<slug>\w+)/$', GetPrize.as_view(), name="prize"),
....

My model:

class Prize(models.Model):
    prize_name = models.CharField(max_length=30, blank=False, null=False, verbose_name="the prize's name")
    prize_slug = models.SlugField(max_length=30, blank=False, null=False, verbose_name="the prize slug")
    prize_excerpt = models.CharField(max_length=100, blank=False, null=False, verbose_name="prize excerpt")
    company = models.ForeignKey('Company')
    prize_type = models.ManyToManyField('Prize_Type')
    def get_absolute_url(self):
        return reverse('omni:reward', kwargs={'slug':self.prize_slug})
    def __str__(self):
        return self.prize_name

And finally, some relevant parts of the template:

class GetPrize(SingleObjectMixin, FormView):
    template_name = 'omninectar/prize.html'
    slug_field = 'prize_slug'
    form_class = Redeem_Form
    model = Prize

Any ideas?

1

There are 1 best solutions below

0
On

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>