πŸ”« Django reverse()와 resolve()

reverse()

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κ°€ λ°œμƒν•œλ‹€.

resolve()

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 μ—λŸ¬λ₯Ό λ°œμƒμ‹œν‚€λŠ” μ½”λ“œμ΄λ‹€.

References


Written by@ugaemi
Record things I want to remember

🐱 GitHubπŸ“š Reading Space