Django链接未找到模块

2024-03-28 20:58:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我的电脑有问题。尝试访问页面时出现以下错误: NoReverseMatch at/admin/r/17/1/

反转参数为“()”且关键字参数为“{slug”的“reward”:找不到u'yummy-cake'}。已尝试1个图案:['奖品/(?P) /$']

如果我手动键入url,我会得到找不到的页面。你知道吗

我的urlconf:

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

我的型号:

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

最后,模板的一些相关部分:

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

有什么想法吗?你知道吗


Tags: nameselffalseurlverbosemodels页面null
1条回答
网友
1楼 · 发布于 2024-03-28 20:58:36

两件事:

  1. Reverse for 'reward' with arguments '()' and keyword arguments '{'slug': u'yummy-cake'}' not found→在get_absolute_url方法中,告诉Django查找名为reward的url模式,它不在urlconf中。把它改成prize,它就可以工作了。

  2. “如果我手动键入url,我将找不到页面”→您的模式是\w+,在documentation中描述为

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.

所以它只匹配字母、数字和下划线。与“美味蛋糕”中的“-”不符。您可以在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>

相关问题 更多 >