[Q_Django -Error] NoReverseMatch

Soly; 독특하게·2021년 10월 11일
post-thumbnail

Exception Type: NoReverseMatch

Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name.

상황:

1.django의 project에서 여러개의 django app들이 존재했고, 이들 app들 폴더 안에 urls.py를 만들어 url들을 분기처리 해주었다.
2. http://127.0.0.1:8000/으로 처음 접속 했을 때 화면이 list.html을 보여준다.

에러나는 list.html > post_all 변수명은 create 한 글들의 객체들이다.

<table>
    <tr>
        <th>번호</th> 
        <th>제목</th>
        <th>작성자</th>
        <th>작성일</th>
    </tr>
    {% for post in post_all %}
    <tr>
        <td>{{ post.id }}</td>
        <td><a href="{% url 'detail' post.id %}">{{post.title}}</td>
        <td>{{post.created_by}}</td>
    </tr>
    {% endfor %}
</table>

문제:

여기서, <a href="{% url 'detail' post.id %}"> 코드가 있는데,
이는 post.title을 클릭하면 detail이라는 path name을 찾아서, 해당하는 곳의 함수에 post.id를 함수 인자로 넘겨준다는 뜻으로 작성했다.
그런데! detail 이라는 path name 을 posts라는 app의 - url.py 로 url을 분기처리한 파일에 지정해주었다. 때문에, 단지 detail이라고 작성하면 path name을 찾을 수 없다.

다음은, posts 폴더의 urls.py 일부분이다.

from .views import detail

app_name = 'posts'

urlpatterns = [
    path('<int:id>/', detail, name="detail"),
]

여기서, path name을 name="detail" 이라고 했지만 app_name = 'posts'을 작성해주었기 때문에 posts detail로 인식하게 된다.

해결:

다음과 같이 href="{% url 'posts:detail' post.id %}"라고 app name을 명시해주면 된다.

<table>
    <tr>
        <th>번호</th> 
        <th>제목</th>
        <th>작성자</th>
        <th>작성일</th>
    </tr>
    {% for post in post_all %}
    <tr>
        <td>{{ post.id }}</td>
        <td><a href="{% url 'posts:detail' post.id %}">{{post.title}}</td>
        <td>{{post.created_by}}</td>
    </tr>
    {% endfor %}
</table>

추가적으로!

템플릿 언어를 사용하지 않는다면, /로 이동하는 url을 작성해주면 된다.
<a href="posts/create/"> url 이동! </a>

profile
협업을 즐겨하는 목표지향적인, Front-End 개발자입니다.

0개의 댓글