[django] DetailView로 profile페이지 구성

Hyeseong·2020년 12월 12일
0

django

목록 보기
3/35
post-thumbnail

목적

DetailView를 이용한 활용과 그 쓰임에 대해 대략적으로 짚어보도록 할게요.

View

from django.views.generic import CreateView, DetailView

# 생략

class AccountDetailView(DetailView):
    model = User
    context_object_name = 'target_user'
    template_name = 'accountapp/detail.html'
  • from django.contrib.auth.models import User에서 가져온 User를 model 값으로 지정하고
  • context_object_name = 'target_user'도 지정해 주는데요. 만약 default값으로 생략해 버리면 user라는 context 값이 template에 전달되는데요. 그럼 내가 다른 사람의 페이지로 가서 구경하고 싶어도 내 정보만 보여주는 문제가 발생해요.

이는 'user'라는 컨텍스트 이름의 모호함 때문이지 않나? 싶어요 그래서 AccountDetailView안에 context_object_name = 'target_user'이라고 좀더 명확하게 표현하고 있어요.

  • template_name은 profile 페이지가 어디에 있는지 해당 경로를 값으로 넘겨주면되요.

accountapp/urls

from django.contrib.auth.views import LoginView, LogoutView
from django.urls import path, include
from accountapp.views import hello_world, AccountCreateView, AccountDetailView

app_name = 'accountapp'

urlpatterns = [
	
	# 생략
    path('detail/<int:pk>/', AccountDetailView.as_view(), name='detail'),
  • <int:pk> 설정으로 고유한 primary key를 기준으로 유저 값을 넘겨 받아(로그인시 받겠조!?) 다시 detail url 뒷부분에 연결되어 DetailView를 호출하여 필요한 계정 프로필 템플릿으로 최종적으로 전달되어 보여지게 되도록하는 구조에요.

Template

accountapp/deatail.html

{% extends 'base.html' %}

{% block content %}

    <div>
	    <div style="text-align: center; max-width: 500px; margin: 4rem auto;">
	    	<p>
                {{target_user.date_joined}}
            </p>
	    	<h2 style="font-family: 'NanumSquareB'">
                {{target_user.username}}
            </h2>
	    </div>
</div>

{% endblock %}

구현된 모습

profile
어제보다 오늘 그리고 오늘 보다 내일...

1개의 댓글

comment-user-thumbnail
2021년 11월 9일

정주행하겠습니다. 좋은 시리즈 글 너무 감사드립니다.

답글 달기