로그인한 후 오른쪽의 회원 정보 창에 프로필 이미지를 추가해주고 해당 이미지를 댓글에서 그대로 사용할 수 있게 구현을 하고 싶었다.
view.py에 새로운 함수를 구현을 하고 url을 연결하고 comment_template.html로 보내주는 작업을 진행했다.
def comment_profile_image(request):
if request.method == 'POST':
print("comment_profile_image 호출됨") # 호출 확인용 로그
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 = {
"user_profile": user_profile,
}
print("user_profile:", context) # 디버깅용 로그
return render(request, "book/comment_template.html, context)
else:
print("POST 요청이 아닙니다.") # POST가 아닐 경우 로그 확인
index함수에서 보내주는 것 처럼 user의 id를 받고 UserProfile의 오브젝트 값을 가져와서 comment_template로 보내주었다.
path('<int:pk>/comment_profile_image/',views.comment_profile_image,name="comment_profile_image"),
위와 같이 url을 연결을 해주었다.
<form method="post" action="{% url 'comment_profile_image' post.pk %}" enctype="multipart/form-data">
<img
src="{% if user_profile.profile_image %} http://127.0.0.1:8000/book{{ user_profile.profile_image }}{% endif %}"
alt="Profile Picture"
style="cursor: pointer; width: 50px; height: 50px; border-radius: 50%;"
>
</form>
위와 같이 코드를 짜서 이미지를 받아오면 된다고 생각했다.
하지만 아무것도 실행이 되지 않았다.
어제 했었던 만큼 오늘은 수월하게 진행될 줄 알았더니 그게 아니었다. 아예 view.py에서 만들었던 함수 자체가 실행이 되지 않았다.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRFToken': '{{ csrf_token }}' // CSRF 토큰 포함
}
});
$.ajax({
url: "{% url 'comment_profile_image' post.pk%}", // 자동으로 호출할 URL
type: 'post',
success: function(response) {
// 성공적으로 호출된 경우의 처리
console.log('응답:', response);
},
error: function(response) {
// 에러 처리
console.log('에러:', response);
}
});
});
</script>
위와 같이 자바 스크립트로 함수를 강제로 실행해주면 해결 될 것이라생각했는데 오류가 발생했다.
'장고' 카테고리의 다른 글
개발 일지 31 - 댓글 프로필 이미지 추가..3 (0) | 2024.09.14 |
---|---|
개발 일지 30 - 댓글 프로필 이미지 추가 ..2 (2) | 2024.09.13 |
개발 일지 28 - 프로필 이미지 오류..3 (0) | 2024.09.11 |
개발 일지 27 - 프로필 이미지 추가 2 (0) | 2024.09.10 |
개발 일지 26 - 프로필 이미지 추가 (0) | 2024.09.09 |