장고

개발 일지 28 - 프로필 이미지 오류..3

sorecord 2024. 9. 11. 09:46

 

더이상 수정할 것도 없을거라 생각했지만 완전히 틀렸다. 

 

 

<form method="post" action="{% url 'upload_profile_pic' %}" enctype="multipart/form-data">
    {% csrf_token %}
    <img 
        src="{% if user_profile.profile_image %}{{ user_profile.profile_image }}{% endif %}" 
        alt="Profile Picture" 
        style="cursor: pointer; width: 100px; height: 100px; border-radius: 50%;" 
        onclick="document.getElementById('file-input').click();"
    >
    <input 
        type="file" 
        id="file-input" 
        name="profile_pic" 
        accept="image/*" 
        onchange="this.form.submit();"
    >
</form>

user_profile이 부분이 아주 말썽이었다. 

 

원래는 UserProfile DB에 있는 user의 값을 받아와서 경로를 사용해야 하는 건데 request.user을 사용할 수 없으니 큰 문제였다. 

 

고민 끝에 생각해낸 해결책은 UserProfile의 객체를 탬플릿 파일로 전송을 시키는 것이었다. 

 

user_id = request.session.get('user_id')


        
    try:
        user_profile = UserProfile.objects.get(user_id=user_id)
    except UserProfile.DoesNotExist:
        
        user_profile = None  # 프로필이 없으면 None으로 설정
        
    context = {
        'page_obj': page_obj,
        'user_profile': user_profile,
    }
    print(context)
    return render(request,'book/index.html',context)

 

위의 코드는 index함수의 일부이다. view.py에 있는 함수이다. 이 함수는 장고가 실행되면 가장 첫번째 화면을 보여줘야 하는 부분이기에 이곳에 UserProfile의 객체를 구해서 context로 보냈다. 

 

경로를 받는 것에는 문제가 없었다. 아주 성공적이었다. 하지만 media이 부분이 문제였다.

 

http://127.0.0.1:8000/media/image.jpg 원래는 이 경로를 인터넷 창에 치면 이미지가 떠야만 프로필 이미지가 성공적으로 바뀔 수 있는데 도저히 해결되지가 않았다. 

 

혹시 하는 마음으로 http://127.0.0.1:8000/book/media/image.jpg book이라는 경로를 추가해주니까 이미지가 출력이 되었다. 

 

원래는 media로 실행이 되는 것이 정상이라고 한다. book을 없애고 원래 경로를 찾으려고 setting의 값도 바꾸고 url의 값도 바꿔보았지만 계속 그대로 였다. 

 

그러다 해결책을 찾았는데 그 방법은 아래와 같다. 

 

src="{% if user_profile.profile_image %} http://127.0.0.1:8000/book{{ user_profile.profile_image }}{% endif %}"

직접 경로를 적어주니 문제없이 프로필 이미지가 만들어지는 것을 확인할 수 있었다.