URL Reverse의 장점
1. 개발자가 일일이 URL을 계산할 필요가 없다
2. URL이 변경되더라도, URL Reverse가 변경된 URL을 추적한다 (누락될 일이 없음)
from django.conf import settings
from django.contrib import admin
from django.conf.urls import include, url
from django.urls import path, include
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('shop/', include('shop.urls')),
path('blog/', include('blog.urls')),
]
# path('myblog/', include('blog.urls')), --> myblog로 바꿔도 코드 수정없이 잘 돌아감
def get_absolute_url(self):
# return reverse('shop:item_detail', args=[self.pk])
return reverse('shop:item_detail', kwargs={'pk': self.pk})
from django.urls import path, register_converter, re_path
from .converters import FourDigitYearConverter
from shop.views import item_list, item_detail, archives_year
register_converter(FourDigitYearConverter, 'yyyy')
app_name = 'shop'
urlpatterns = [
path('archives/<yyyy:year>/', archives_year, name='archives_year'),
path('', item_list, name='item_list'),
path('<int:pk>/', item_detail, name='item_detail'),
]
# path('detail/<int:pk>/', item_detail, name='item_detail') --> detail 추가되도 코드 수정 안해도됨(reverse니깐)
<ul>
{% for item in item_list %}
<li>
<a href="{{ item.get_absolute_url }}">
{{ item.name }}
</a>
{{ item.price }}
{{ item.desc }}
</li>
{% endfor %}
</ul>