# 采坑日记
# Django url模块加载时机
from django.shortcuts import render
from django.urls import reverse
from django.shortcuts import redirect
# 试图在这里获取URL
page = reverse('myapp:index')
def index(request):
return render(request, 'myapp/index.html')
def re_index(request):
# 然后在这里重定向
return redirect(page)
# 报错信息:
# django.core.exceptions.ImproperlyConfigured:
# The included URLconf 'mysite.urls' does not appear to have any patterns in it.
# If you see valid patterns in the file then the issue is probably caused by a circular import.
Django官方文档:
# Django 如何处理一个请求
当一个用户请求Django 站点的一个页面,下面是Django 系统决定执行哪个Python 代码使用的算法:
- Django 确定使用根 URLconf 模块。通常,这是
ROOT_URLCONF设置的值,但如果传入HttpRequest对象拥有urlconf属性(通过中间件设置),它的值将被用来代替ROOT_URLCONF设置。- Django 加载该 Python 模块并寻找可用的
urlpatterns。它是django.urls.path()和(或)django.urls.re_path()实例的序列(sequence (opens new window))。- Django 依次匹配每个URL 模式,在与请求的URL 匹配的第一个模式停下来。
- 一旦有 URL 匹配成功,Djagno 导入并调用相关的视图,这个视图是一个简单的 Python 函数(或基于类的视图class-based view)。视图会获得如下参数:
- 一个
HttpRequest实例。- 如果匹配的 URL返回没有命名组,那么来自正则表达式中的匹配项将作为位置参数提供。
- 关键字参数由路径表达式匹配的任何命名部分组成,并由
django.urls.path()或django.urls.re_path()的可选kwargs参数中指定的任何参数覆盖。- 如果没有 URL 被匹配,或者匹配过程中出现了异常,Django 会调用一个适当的错误处理视图。参加下面的错误处理( Error handling )。
这里重点在于:
只有当用户发起请求的时候,Django才会加载ROOT_URLCONF并寻找可用的urlpatterns。
所以代码中的问题是:
执行reverse的时候并没有用户发起请求,因而没有加载url模块,导致无法找到相应的URL。
← 视图函数