视图命名与路由命名的区别
时间: 2023-09-21 21:11:20 浏览: 46
视图命名和路由命名都用于标识一个视图或路由的名称,但它们的作用和使用场景有所不同。
视图命名是给视图取一个易于记忆的名称,方便在代码中使用。视图命名一般在定义视图函数时使用,例如:
```python
from django.urls import path
from . import views
urlpatterns = [
path('articles/<int:year>/', views.year_archive, name='year_archive'),
path('articles/<int:year>/<int:month>/', views.month_archive, name='month_archive'),
path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail, name='article_detail'),
]
```
这里的视图函数分别被命名为 `year_archive`、`month_archive` 和 `article_detail`,这样在模板中就可以使用这些视图名称来生成 URL 了,例如:
```html
<a href="{% url 'year_archive' 2015 %}">2015年度文章归档</a>
```
这样就会生成一个 URL:`/articles/2015/`。
路由命名是给路由取一个易于记忆的名称,方便在代码中使用。路由命名一般在定义路由时使用,例如:
```python
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('about/', views.about, name='about'),
path('contact/', views.contact, name='contact'),
]
```
这里的路由分别被命名为 `index`、`about` 和 `contact`,这样在视图函数中就可以使用这些路由名称来生成 URL 了,例如:
```python
from django.shortcuts import render, redirect
from django.urls import reverse
def my_view(request):
return redirect(reverse('about'))
```
这样就会生成一个 URL:`/about/`。路由命名主要用于在视图函数中生成 URL,而视图命名主要用于在模板中生成 URL。