티스토리 뷰

반응형

지금까지 우리는 회원가입(UserCreationForm)을 구현했고, 가입된 ID의 프로필부분(Detail)을 구현할 것이다. 사실 유저를 보여주기만 하면 되므로 쉽게 구현가능하다.

 

 

1:N과 N:M까지 공부를 마쳤다면 아래부분에 구현한 심화부분을 다시 보는 것을 추천한다. 초기 detail.html 코드부터 나중에 좋아요와 팔로우 기능 구현까지 적용된 detail.html까지 여러 가지를 넣어둘 예정이고 계속 추가할 예정이다. 필요한 부분을 쓰면 된다. 

 

 

 

2021/01/05 - [Web/Django] - [Django]사용자인증관리_signup(회원가입)_UserCreationForm

기본적으로 아래의 코드는 회원가입 이후에 추가되는 코드다. 참고하고 와도 좋다.

 

 

accounts/urls.py

app_name = 'accounts'
urlpatterns = [
    path('signup/', views.signup, name='signup'),
    path('<int:pk>/', views.detail, name='detail'),
]

 기본적으로 detail 부분은 user의 개인에 대한 프로필 정보이기 때문에 '<int:pk>'를 path로 한다.

 

 

 

accounts/views.py

from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import get_user_model
# from django.contrib.auth.models import User


def detail(request, pk):
    User = get_user_model()
    user = get_object_or_404(User, pk=pk)
    context = {
        'user': user
    }
    return render(request, 'accounts/detail.html', context)

User를 바로 가져와서 써도 되지만 우리는 않쓰고 get_user_model을 쓴다. user모델을 가져다 쓸 수 있는 내장함수가 get_user_model에 저장되어 있다. 즉, 일반적으로

 

from django.contrib.auth import get_user_model

 

를 쓴다. 유저 model을 가져오는 함수가 있다. import 시 유저(User)를 통해 가져오는게 아니라 함수(get_user_model)를 통해 가져온다. 왜냐하면 나중에 외부에서 재정의 하기위함이다.

 

정리하면, 현재는 User나 get_user_model()와의 차이가 없다. 그러나 우리는 프로젝트 시 다양한 확장성을 위해서 get_user_model()을 쓰는 습관을 들인다고 생각해주면 된다.

 

 

 

accounts/templates/accounts/detail.html

{% extends 'base.html' %}
{% block body %}
<h1>{{ user.pk }} : {{ user.username }}</h1>
<hr>
{% endblock %}

사실 위의 내용은 사용자편의에 따라 자유롭게 작성해주면된다. 위에서의 user는 views에서 받아온 user이다.

 

 

 

 


 

위의 내용까지가 기초이다. 만약 아래의 내용이 정리가 됐다면, 최종 detail.html을 확인해 보자.

2020/08/23 - [Web/Django] - [Django]데이터베이스관리(1:N)_User와 Article

2020/08/24 - [Web/Django] - [Django]데이터베이스관리(1:N)_댓글 기능 추가하기

2020/08/27 - [Web/Django] - [Django]데이터베이스관리(N:M)_기초개념

2020/08/28 - [Web/Django] - [Django]데이터베이스관리(N:M)_좋아요 기능 구현

2020/08/29 - [Web/Django] - [Django]데이터베이스관리(N:M)_팔로우 기능 구현(custom user)

 

좋아요 기능과 팔로우 기능 을 구현 후의 detail.html은 아래와 같다.

{% extends 'base.html' %}

{% block body %}
<h1>{{ user.pk }} : {{ user.username }}</h1>
{% with user_followers=user.followers.all %}
    {% if request.user == user %}
        <a href="{% url 'accounts:update' %}">회원 수정</a>
        <form action="{% url 'accounts:delete' %}" method="POST">
            {% csrf_token %}
            <button class="btn btn-secondary">회원 탈퇴</button>
        </form>
    {% else %}
        <hr>
            {% if request.user in user_followers %}
                <a href="{% url 'accounts:follow' user.pk %}">팔로우 취소</a>
            {% else %}
                <a href="{% url 'accounts:follow' user.pk %}">팔로우</a>
            {% endif %}
    {% endif %}
    <p> {{ user_followers|length }}명이 팔로우하고 있습니다.</p>
    <p> {{ user.followings.count }}명을 내가 팔로우하고 있습니다.</p>
{% endwith %}
<hr>
<h3>작성한 글 목록</h3>
{% for article in user.article_set.all %}
    <a href="{% url 'articles:detail' article.pk %}">
        <p>{{ article.title }}</p>
    </a>
{% endfor %}
<h3>좋아요한 글 목록</h3>
{% for article in user.like_articles.all %}
    <a href="{% url 'articles:detail' article.pk %}">
        <p>{{ article.title }}</p>
    </a>
{% endfor %}
{% endblock %}

 

 

 

 

다음은 회원정보 수정 부분을 배워보자.

han-py.tistory.com/147

 

[Django]사용자인증관리_Update, 유저정보수정(UserChangeForm)

0. 들어가면서 일단 Article부분처럼 Create와 Update를 합칠 수 없다. 왜냐하면 create는 password를 2개 받는데 update는 그런게 없기 때문이다. 기본적으로 User를 변경하기 위한 Form이 있다. 바로 UserChangF..

han-py.tistory.com

 

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함