Reference resources Django The teaching video shall be analyzed in reverse, and errors shall be reported in the steps . The code is as follows :
1. Total project route MyBlog/urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('users/', include('users.urls')),
path('', include('blog.urls'))
]
2. Application sub route blog/urls.py
urlpatterns = [
path('', views.index, name='index'),
path('test/', views.test, name='test'),
]
3. Apply view file blog/views.py
def index(request):
return redirect(reverse('test')) # Home page redirection
def test(request):
return HttpResponse('test')
Error message :
NoReverseMatch at /
Reverse for 'test' not found. 'test' is not a valid view function or pattern name.
Assign an... To the application app_name, And in the general route of the project include Function configuration namespace For the application name app_name, Finally, use... In the application view file “ Applied namespace: Redirect url Of name” Format to achieve reverse parsing . The modified code is as follows :
1. Total project route MyBlog/urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('users/', include('users.urls')),
path('', include('blog.urls', namespace='blog'))
]
2. Application sub route blog/urls.py
app_name = 'blog' # Define a namespace , Used to distinguish link addresses between different applications
urlpatterns = [
path('', views.index, name='index'),
path('test/', views.test, name='test'),
]
3. Apply view file blog/views.py
def index(request):
return redirect(reverse('blog:test'))
def test(request):
return HttpResponse('test')
The modified running results :