python μ½λ μμμ URL ν νλ¦Ώ νκ·Έμ λΉμ·νκ² λμνλ κΈ°λ₯μ΄λ€.
from news import views
path('archive/', views.archive, name='news-archive')
urls.py
μμ μ€μ ν URLμ name
μ΄λ, viewnameμ ν΅ν΄μ λ€μ URLλ‘ λλ릴 μ μλ€.
# name μ¬μ© μ
reverse('news-archive')
# viewname μ¬μ© μ
from news import views
reverse(views.archive)
μΈμκ° μλ URLμ΄λΌλ©΄ λ€μκ³Ό κ°μ΄ args
λ₯Ό ν¬ν¨ν μ μλ€.
from django.urls import reverse
def myview(request):
return HttpResponseRedirect(reverse('arch-summary', args=[1945]))
kwargs
λ‘ μ λ¬νλ κ² λν κ°λ₯νλ€.
νμ§λ§ args
μ kwargs
λ₯Ό λμμ μ λ¬ν μλ μλ€.
>>> reverse('admin:app_list', kwargs={'app_label': 'auth'})
'/admin/auth/'
μΌμΉνλ URLμ΄ μμΌλ©΄ NoReverseMatch
κ° λ°μνλ€.
reverse()
μλ λ°λλλ κΈ°λ₯μ νλ€.
ResolverMatch
κ°μ²΄μ url_name
μ ν΅ν΄ ν΄λΉ URL pathμ μΌμΉνλ μ΄λ¦μ λ°μ μ μλ€.
match = resolve('/some/path/')
print(match.url_name)
ResolverMatch
ν΄λμ€μλ url_name
μ΄μΈμλ λ§μ λ©μλκ° μλ€. (νμ λ§ν¬ μ°Έκ³ )
μ΄λ¬ν λ©μλλ₯Ό μ΄μ©ν΄ resolve()
ν¨μλ₯Ό μ΄μ©ν΄μ viewμμ μ€λ₯κ° λ°μνλμ§ ν
μ€νΈν΄λ³Ό μ μλ€.
from urllib.parse import urlparse
from django.urls import resolve
from django.http import Http404, HttpResponseRedirect
def myview(request):
next = request.META.get('HTTP_REFERER', None) or '/'
response = HttpResponseRedirect(next)
view, args, kwargs = resolve(urlparse(next)[2])
kwargs['request'] = request
try:
view(*args, **kwargs)
except Http404:
return HttpResponseRedirect('/')
return response
μ μ½λλ URL ν¨ν΄κ³Ό μΌμΉνλ viewλ₯Ό μ€νν΄μ μ€λ₯κ° λλ©΄ Http404
μλ¬λ₯Ό λ°μμν€λ μ½λμ΄λ€.