2020-03-30

Django 13. 프로필보기 / 수정 구현

Django 내장폼인 UserChangeForm을 사용해 사용자 프로필보기와 수정을 구현합니다.


1. 프로필보기 구현하기

Profile 템플릿을 render하는 views.py에 아래와 같이 소스를 입력합니다.

1
2
3
4
5
6
# users/views.py

@login_message_required
def profile_view(request):
if request.method == 'GET':
return render(request, 'users/profile.html')

Decorator로 로그인되지 않은 사용자의 접근을 막고 GET 요청이 들어오면 profile.html을 render합니다. 템플릿에서는 현재 사용자의 정보를 { { user.<필드명> } } 형식으로 조회가 가능합니다. templatesusersprofile.html을 생성하고 아래와 같이 소스를 입력합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!-- templates/users/profile.html -->

<table>
<tr>
<td>아이디</td>
{% if user.level == '0'%}
<td>{{ user.user_id }}(개발자)</td>
{% elif user.level == '1' %}
<td>{{ user.user_id }}(관리자)</td>
{% else %}
<td>{{ user.user_id }}</td>
{% endif %}
</tr>
<tr>
<td>이메일</td>
<td>{{ user.email }}</td>
</tr>
<tr>
<td>이름</td>
<td>{{ user.name }}</td>
</tr>
</table>

위와 같은 형식으로 조회할 users 모델의 필드명을 입력합니다.

2. 프로필수정 forms.py 작성

회원정보수정 템플릿에 적용할 form을 작성하기 위해 django.auth의 UserChangeForm을 상속받는 폼클래스를 forms.py에 아래와 같이 추가합니다.

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
# users/forms.py

from django.contrib.auth.forms import UserChangeForm
from .choice import *

class CustomCsUserChangeForm(UserChangeForm):
password = None
hp = forms.IntegerField(label='연락처', widget=forms.NumberInput(
attrs={'class': 'form-control', 'maxlength':'11', 'oninput':"maxLengthCheck(this)",}),
)
name = forms.CharField(label='이름', widget=forms.TextInput(
attrs={'class': 'form-control', 'maxlength':'8',}),
)
student_id = forms.IntegerField(label='학번', widget=forms.NumberInput(
attrs={'class': 'form-control', 'maxlength':'8', 'oninput':"maxLengthCheck(this)",}),
)
grade = forms.ChoiceField(choices=GRADE_CHOICES, label='학년', widget=forms.Select(
attrs={'class': 'form-control',}),
)
circles = forms.ChoiceField(choices=CIRCLES_CHOICES, label='동아리', widget=forms.Select(
attrs={'class': 'form-control',}),
)

class Meta:
model = User()
fields = ['hp', 'name', 'student_id', 'grade', 'circles']

아이디와 메일 등 변경되어서는 안되는 필드들은 Meta 클래스 내에 표기하지 않습니다.

Django 내장폼 공식문서

3. 프로필수정 views.py 작성

views.py에 아래와 같이 프로필 수정 view의 소스를 입력합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# users/views.py

from .forms import CustomCsUserChangeForm

@login_message_required
def profile_update_view(request):
if request.method == 'POST':
user_change_form = CustomCsUserChangeForm(request.POST, instance = request.user)

if user_change_form.is_valid():
user_change_form.save()
messages.success(request, '회원정보가 수정되었습니다.')
return render(request, 'users/profile.html')
else:
user_change_form = CustomCsUserChangeForm(instance = request.user)

return render(request, 'users/profile_update.html', {'user_change_form':user_change_form})

(원래의 소스는 컴퓨터공학부와 일반사용자의 form이 각각 구분되어 있습니다. 이 포스팅에서는 일반사용자의 form은 제외하고 포스팅하겠습니다.)

마찬가지로 decorator를 추가하고 사용자가 수정하기 버튼을 클릭했을시 사용자의 정보들이 이전에 생성한 CustomCsUserChangeForm에 담겨야 하기에 instance = request.user 소스를 삽입합니다. 회원정보가 수정되면 UserChangeForm에서 검증을 해주며 성공하면 message와 함께 다시 프로필창으로 이동합니다.

4. urls.py 작성

각각의 view와 url을 연결하기 위해 urls.pyurlpatterns에 아래의 path를 추가합니다.

1
2
3
4
# users/urls.py

path('profile/', views.profile_view, name='profile'),
path('profile/update/', views.profile_update_view, name='profile_update'),

5. 결과

django-project-13

*전체 html, css 등은 자세하게 포스팅하지 않습니다. 제 Github에서 소스를 확인하실 수 있습니다.