기존에 만들었던 게시판에 프로필화면을 만들어 조회와 수정을 할 수 있도록 하려고 한다.
Install
pip install pillow
models.py
#models.py
#프로필
class Profile(models.Model):
"""
유저아이디
프로필이미지
프로필소개글
"""
user = models.OneToOneField(User,on_delete=models.CASCADE)#유저와 1:1 join
profile_img = models.ImageField(blank=True,upload_to="images/")
profile_content = models.TextField(blank=True)
DB적용
python manage.py makemigrations
python manage.py migrate
admin.py
# admin.py
from django.contrib import admin
from .models import User,Profile
admin.site.register(User)
admin.site.register(Profile)
urls.py
#urls.py
#프로필
path('profile_detail/<int:user_id>>',views.profile_detail,name='profile_detail'),
path('profile_modiry/<int:user_id>/',views.profile_modify,name='profile_modify'),
views.py
from django.shortcuts import render,redirect,get_object_or_404
from django.contrib.auth import authenticate,login
from common.forms import UserForm,ProfileForm
from django.contrib.auth.decorators import login_required
from .models import Profile
#회원가입
def singup(request):
if request.method == "POST":
form = UserForm(request.POST)
if form.is_valid():
user_profile = form.save()
Profile.objects.create(user=user_profile) #프로필 생성
username = form.cleaned_data.get('username') #form.cleaned_data.get //개별적으로 값을 얻고 싶을 경우 사용
raw_password = form.cleaned_data.get('password1')
user = authenticate(request, username = username,password=raw_password)#사용자 인증
login(request,user,backend='django.contrib.auth.backends.ModelBackend')#로그인
return redirect('/')
else:
form = UserForm()
return render(request,'common/signup.html',{'form':form})
# Create your views here.
#프로필 조회
@login_required(login_url="common:login")
def profile_detail(request,user_id):
profile = get_object_or_404(Profile,user_id = user_id)#로그인중인 아이디랑 프로필유저아이디를 비교하여 같은것을 가져온다
context = {"profile":profile}
return render(request,"common/profile_detail.html",context)
회원가입을 했을경우 대칭되는 프로필이 동시에 생성되게 하기 위해 회원가입을 한 후 프로필이 생성되게 하였다.
정상적으로 출력이 되는지 확인하기 위해 기존에 있던 아이디에 프로필을 추가했다.
하지만 이상태로만 사용하게 된다면 이미지는 나오지 않으므로 이미지가 나올 수 있도록 작업을 해 줄 것이다.
settings.py
#미디어파일이 저장되는 경로를 설정
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
project.urls.py
#media
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
#로그인
path('login/',auth_views.LoginView.as_view(template_name = 'common/login.html'),name = 'login'),
path('logout/',auth_views.LogoutView.as_view(),name = 'logout'),
path('signup/',views.singup,name="signup"),
#프로필
path('profile_detail/<int:user_id>>',views.profile_detail,name='profile_detail'),
path('profile_modiry/<int:user_id>/',views.profile_modify,name='profile_modify'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
마지막줄의 + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)가 핵심이다
작업을 다 마치고 프로필에 사진을 추가하게 된다면
media에 파일이 추가가 이미지 파일이 추가가 될 것 이다.(파일의 저장위치는 models.py의 profile_img속성을 보면 알 수 있다.)
정상적으로 작동하는지 확인용으로 간단한 템플릿을 만들어 사용하였다.
profile_detail.html
{% extends 'base/base.html' %}
{% block content %}
<div class="container">
<h5 class="my-3 border-bottom pd-2">프로필</h5>
<div class="mb-3">
<label for="profile_img" class="form-label">프로필 사진</label>
<br>
<img class="image" src="{{ profile.profile_img.url }}" width=300px, height=300px/>
</div>
<div class="mb-3">
<label for="nickname" class="form-label">닉네임</label>
<input type="text" class="form-control" name="nickname" id="nickname" disabled
value = "{{profile.user.nickname|default_if_none:''}}">
</div>
<div class="mb-3">
<label for="profile_content" class="form-label">소개글</label>
<textarea class="form-control" name="profile_content" disabled
id="profile_content" rows="10">{{profile.profile_content|default_if_none:'' }}</textarea>
</div>
<button type="submit" class="btn btn-primary">수정하기</button>
</div>
{% endblock %}
정상적으로 동작한다.
다음 글로는 프로필 수정을 해보자.
'Django > Django study' 카테고리의 다른 글
[Django] 친구추가, 팔로우 목록조회 (0) | 2022.12.07 |
---|---|
[Django]회원 프로필 수정 (0) | 2022.11.27 |
[Django] User Custom (0) | 2022.11.24 |
Django-allauth 소셜로그인 (0) | 2022.11.15 |
[Django] 앱 생성 후 view,template 연결 (0) | 2022.10.28 |