๐ ๋ณธ ํฌ์คํธ๋ ๋ฆฌ์กํธ์ ํจ๊ป ์ฅ๊ณ ์์ํ๊ธฐ Complete + ๋ณ๋๋ก ๊ณต๋ถํ ๋ด์ฉ์ผ๋ก ์ด๋ฃจ์ด์ ธ์์ต๋๋ค
urls.py ๋ณ๊ฒฝ๋ง์ผ๋ก๋ ๊ฐ ๋ทฐ์ ๋ํ URL์ด ๋ณ๊ฒฝ๋๋ ์ ์ฐํ URL ์์คํ
<a href= '{% url "blog:post_detail" post.id %}'>{{post.message}}</a>
from django.urls import reverse
reverse('blog:post_detail', args = [100])
reverse('blog:post_detail', kwargs = {'pk':100})
reverse('blog:post_detail) #NoReverseMatch
from django.shortcuts import resolve_url
resolve_url('blog:post_detail', 100)
resolve_url('blog:post_detail', pk=100)
from django.shortcuts import redirect
redirect('blog:post_detail', 100)
redirect('blog:post_detail", pk=100)
# <HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/blog/100/">
์ด๋ค ๋ชจ๋ธ์์ Detail๋ทฐ ์์ฑํ ๊ฒฝ์ฐ, Detail๋ทฐ์ ๋ํ URLConf ์ค์ ํ์๋ง์
get_absolute_url
์ค์ ํ๊ธฐ
resolve_url(๋ชจ๋ธ์ธ์คํด์ค)
, redirect(๋ชจ๋ธ์ธ์คํด์ค)
๋ฅผ ํตํด ๋ชจ๋ธ ์ธ์คํด์ค์ get_absolute_url() ํจ์ ์๋์ผ๋ก ํธ์ถ
resolve_url
ํจ์๋ ๋จผ์ get_absolute_url()
ํจ์ ์กด์ฌ ์ฌ๋ถ๋ฅผ ์ฒดํฌํ๊ณ
์กด์ฌํ๋ ๊ฒฝ์ฐ reverse๋ฅผ ์ํํ์ง ์๊ณ ๊ทธ ๋ฆฌํด๊ฐ์ ์ฆ์ ๋ฆฌํด
def resolve_url(to, *args, **kwargs):
# ...
if hasattr(to, 'get_absolute_url'):
return to.get_absolute_url()
# ...
get_absolute_url()์ ์ฌ์ฉํ๋ฉด ์๋์ฒ๋ผ ์ฌ์ฉ ๊ฐ๋ฅ
resolve_url('blog:post_detail', pk=post.pk)
=> resolve_url(post)
redirect('blog:post_detail', pk=post.pk)
=> redirect(post)
{% url 'blog:post_detail' post.pk%}
=> {{ post.get_absolute.url }}
์์ 1
from django.urls import reverse
class Post(models.Model):
#...
def get_absolute_url(self):
return reverse('instagram:post_detail', args=[pk.self])
<a href ={{post.get_absolute_url}}>{{post.message}}</a>
์์ 2
์ฐธ๊ณ
https://wayhome25.github.io/django/2017/05/05/django-url-reverse/