profile
앱을 생성하기 위해 manage.py
파일이 있는 경로에서 해당 앱을 생성하는 명령어를 실행합니다.
python manage.py startapp profile
생성한 앱의 이름을 settings.py
파일의 INSTALLED_APPS
리스트 변수에 추가합니다.
profile
앱의 모델을 정의합니다.
Profile
모델은 User
모델과 일대일 관계를 가지며, user
필드를 사용하여 연결합니다.image
필드는 이미지 파일을 업로드하는 경우 해당 파일이 저장되는 경로의 디렉토리를 지정합니다.nickname
필드는 최대 길이가 20인 문자열 필드로, 고유한 값을 가지도록 설정합니다.message
필드는 최대 길이가 100인 문자열 필드입니다.related_name
은 User
객체를 참조할 때 사용되는 값으로, 기본적으로는 해당 클래스의 소문자이름_set으로 설정됩니다. 여기서는 별도의 이름으로 profile
을 설정하였습니다.profileapp/forms.py
파일에 프로필 생성을 위한 폼을 정의합니다.
ProfileCreationForm
은 forms.ModelForm
을 상속받은 클래스로, Profile
모델과 연결됩니다.Meta
클래스에서 model
변수에 Profile
모델을 지정하고, fields
변수에 폼에서 사용할 필드를 지정합니다.from django.contrib.auth.models import User
from django.db import models
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
image = models.ImageField(upload_to='profile/', null=True)
nickname = models.CharField(max_length=20, unique=True, null=True)
message = models.CharField(max_length=100, null=True)
from django import forms
from profileapp.models import Profile
class ProfileCreationForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image', 'nickname', 'message']
profile
앱 생성settings.py
및 프로젝트 urls.py
설정models.py
에 Profile
클래스 및 필드 정의forms.py
에 ProfileCreationForm
폼 생성from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView
from profileapp.forms import ProfileCreationForm
from profileapp.models import Profile
class ProfileCreateView(CreateView):
model = Profile
context_object_name = 'target_profile'
form_class = ProfileCreationForm
success_url = reverse_lazy('accountapp:hello_world')
template_name = 'profileapp/create.html'
def form_valid(self, form):
temp_profile = form.save(commit=False)
temp_profile.user = self.request.user
temp_profile.save()
return super().form_valid(form)
ProfileCreateView
클래스를 작성합니다. 이 클래스는 CreateView
를 상속합니다.model
변수에 Profile
모델을 연결합니다.context_object_name
변수에 컨텍스트 변수명을 지정합니다.form_class
변수에 우리가 만든 ProfileCreationForm
폼 클래스를 할당합니다.success_url
변수에 프로필 생성 성공 시 이동할 페이지의 URL을 지정합니다.template_name
변수에 구현할 템플릿 파일의 경로를 지정합니다.form_valid
메서드를 오버라이드하여 폼 데이터를 처리합니다. 임시로 저장한 후에 유저 정보를 할당하고 저장합니다.{% extends 'base.html' %}
{% load bootstrap4 %}
{% block content %}
<div style="text-align: center; max-width: 500px; margin: 4rem auto">
<div class="mb-4">
<h4>Profile Create</h4>
</div>
<form action="{% url 'profileapp:create' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% bootstrap_form form %}
<input type="submit" class="btn btn-dark rounded-pill col-6 mt-5">
</form>
</div>
{% endblock %}
from django.contrib import admin
from django.urls import path
from profileapp.views import ProfileCreateView
app_name = 'profileapp'
urlpatterns = [
path('create/', ProfileCreateView.as_view(), name='create'),
]
{% extends 'base.html' %}
{% block content %}
<div>
<div style="text-align: center; max-width: 500px; margin: 4rem auto;">
<p>
{{target_user.date_joined}}
</p>
{% if target_user.profile %}
<h2 style="font-family: 'NanumSquareB'">
{{target_user.profile.nickname}}
</h2>
{% else %}
<a href="{% url 'profileapp:create' %}"><h4 style="font-family: 'NanumSquareB'">Create Profile</h4></a>
{% endif %}
{% if target_user == user %}
<a href="{% url 'accountapp:update' pk=target_user.pk %}">
<p>Account Info</p>
</a>
<a href="{% url 'accountapp:delete' pk=target_user.pk %}">
<p>Delete</p>
</a>
{% endif %}
</div>
</div>
{% endblock %}