/school/new-school/ 处的 Django NoReverseMatch

Django NoReverseMatch at /school/new-school/

我的方法有什么问题?

当我 post 新数据时,我希望它 return 返回到输入字段为空的页面。但它给了我这个错误

NoReverseMatch at /school/new-school/

Reverse for 'new-school' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

这是我的模型。请注意,reverse_lazy 已导入

class SchoolList(models.Model):
    name = models.CharField(max_length=15, null=False) 

    def __str__(self):
        return '%s' % (self.name)

    def get_absolute_url(self):
        return reverse_lazy('new-school') 

这是我的url.py

url(r'^school-list/$', SchoolListtView.as_view(), name='school-list'),   
url(r'^new-school/$', CreateSchoolListView.as_view(), name='new-school'),       
url(r'^school(?P<pk>\d+)/update/$', SchoolListUpdate.as_view(), name='update-school')

这是我对创建的看法。

class CreateSchoolListView(CreateView):
    template_name = 'school\create_form.html'
    model = SchoolList
    fields = ['name']

这就是我在模板中指定 url 的方式。

<a href="{% url 'school:new-school' %}">Create New School</a>
<a href="{% url 'school:school-list' %}">View all Schools</a>

当页面显示时,我可以点击链接,它会转到正确的页面。但是当我 post 一个数据时,它会抛出上述错误。我已经研究了好几个小时,并在线阅读了许多答案。看来我的是个例。

尝试将命名空间添加到 get_absolute_url()。

def get_absolute_url(self):
    return reverse_lazy('school:new-school') 

确保将应用的 url 导入到项目的 url 中,命名空间如下:

url(r'^school/', include('school.urls', namespace="school"))

像这样在模板中使用命名空间:{% url 'school:new-school' %}

或删除命名空间:

url(r'^school/', include('school.urls'))

在模板中使用不带名称空间的url:{% url 'new-school' %}

在这种情况下使用 get_absolute_url 将是一个糟糕的方法,因为它是一个实例方法,旨在为单个模型实例获取 url。

如果你想给模型添加方法,你应该使用这样的东西:

@classmethod
def get_create_url(cls):
    return reverse_lazy('school:new-school')