Meme's IT

[Django] N:M 프로필 만들기 본문

BackEnd/Django

[Django] N:M 프로필 만들기

Memez 2023. 10. 17. 09:33
# accounts/urls.py

urlpatterns = [
	...
    path('profile/<username>/',views.profile,name="profile"),
]

여기서 왜 바로 '<username>/'으로 안하고 'profile/<username>'의 형식인가?

그렇게 하면 밑에 다른게 왔을 때 실행이 안된다

위에서 부터 진행하는데 밑에 있는 함수가 username인지 그 함수인지를 알 수 없기 때문에

 

# accounts/views.py
from .forms import get_user_model

def profile(request, username):
    # user의 detail 페이지
    # user를 조회
    User = get_user_model()
    person = User.objects.get(username=username)
    context = {
        'person' : person,
    }
    return render(request,'accounts/profile.html',context)
<!-- profile.html의 body -->


<h1>{{person.username}}님의 프로필</h1>
<hr>
<h2>작성한 게시글</h2>
{% for article in person.article_set.all %}
    <p>{{article.title}}</p>
{% endfor %}
<h2>작성한 댓글</h2>
{% for comment in person.comment_set.all %}
    <p>{{comment.content}}</p>
{% endfor %}
<h2>좋아요를 누른 게시글</h2>
{% for article in person.like_articles.all %}
    <p>{{article.title}}</p>
{% endfor %}

 

내 프로필로 바로 가는 링크 만들기

<!-- articles/index.html -->

<h3>{{ user.username }}님 안녕하세요!</h3>
<a href="{% url "accounts:profile" request.user.username %}">내 프로필</a>

각 글에서 작성자의 프로필 보기

<!-- articles/detail.html -->

<p>작성자 : 
  <a href="{% url "accounts:profile" article.user.username %}">{{article.user}}</a>
</p>

작성자에 a태그 추가

작성자 프로필로 갈 수 있음