我的方法有什么问题?
当我发布新数据时,我希望它返回到输入文件为空的页面。但它给了我这个错误
NoReverseMatch /学校/新学校/ 相反的‘新学校’与参数‘()和关键字参数'{}’不找到。0已尝试的模式:[]
这是我的模型。请注意,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']我就是这样在模板中指定urls的。
<a href="{% url 'school:new-school' %}">Create New School</a>
<a href="{% url 'school:school-list' %}">View all Schools</a>当显示页面时,我可以单击链接,它将转到正确的页面。但是当我发布一个数据时,它会抛出上面的错误。我已经写了好几个小时了,在网上读到了很多答案。看来我的案子很独特。
发布于 2015-12-18 05:40:24
尝试向get_absolute_url()添加命名空间。
def get_absolute_url(self):
return reverse_lazy('school:new-school') 发布于 2015-12-18 06:23:05
请确保在项目的urls中导入应用程序的urls,名称空间如下:
url(r'^school/', include('school.urls', namespace="school"))在模板中使用命名空间,如:{% url 'school:new-school' %}
或删除命名空间:
url(r'^school/', include('school.urls'))在模板中使用没有命名空间的url:{% url 'new-school' %}
在这种情况下,使用url是一种糟糕的方法,因为它是一个实例方法,用于获取单个模型实例的url。
如果要将方法添加到模型中,则应使用以下内容:
@classmethod
def get_create_url(cls):
return reverse_lazy('school:new-school')https://stackoverflow.com/questions/34348647
复制相似问题