Nonamed Develog
[TIL][240822] 프로필 이미지 반응형으로 변경하기 본문
추후 정리
def profile(request, username):
member = get_object_or_404(get_user_model(), username=username)
profile_image = Profile.objects.filter(user=member).last()
if request.method == "POST":
form = ProfileImageForm(request.POST, request.FILES, instance=profile_image)
if form.is_valid():
profile_image = form.save(commit=False)
profile_image.user = member
profile_image.save()
return redirect("users:profile", username=member.username)
else:
form = ProfileImageForm(instance=profile_image)
context = {
"member": member,
"date_joined": member.date_joined,
"form": form,
"profile_image": profile_image,
}
return render(request, "users/profile.html", context)
{% extends 'base.html' %}
{% load static %}
{% block content %}
<h1>{{ member.username }}의 프로필</h1>
{% if profile_image and profile_image.image %}
<img id="profile-img" src="{{ profile_image.image.url }}" alt="profile_image" style="cursor: pointer;" />
{% else %}
<img id="profile-img" src="{% static 'users/user_profile.png' %}" alt="default_profile_image" style="cursor: pointer;" />
{% endif %}
<br />
{% if request.user == member %}
<!-- 파일 입력 필드를 숨김 -->
<form id="profile-form" action="{% url 'users:profile' member.username %}" method="POST" enctype="multipart/form-data" style="display: none;">
{% csrf_token %}
<input type="file" id="id_image" name="image" accept="image/*" style="display: none;" />
<input type="submit" value="이미지 변경" />
</form>
{% endif %}
<br />
<br />
<p>사용자: {{ member.username }}</p>
<p>가입일: {{ date_joined|date:'SHORT_DATE_FORMAT' }}</p>
<p>팔로워: {{ member.followers.count }}</p>
<p>팔로잉: {{ member.followings.count }}</p>
{% if request.user != member %}
<form action="{% url 'users:follow' member.pk %}" method="POST">
{% csrf_token %}
{% if request.user in member.followers.all %}
<input type="submit" value="Unfollow" />
{% else %}
<input type="submit" value="Follow" />
{% endif %}
</form>
{% endif %}
<script>
document.getElementById('profile-img').onclick = function () {
// 파일 선택 창을 엽니다.
document.getElementById('id_image').click()
}
document.getElementById('id_image').onchange = function () {
// 파일이 선택되면 자동으로 폼을 제출합니다.
document.getElementById('profile-form').submit()
}
</script>
{% endblock %}
from django.db import models
from django.conf import settings
# Create your models here.
class Profile(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="profiles")
image = models.ImageField(upload_to="images/", blank=True)
from django import forms
from .models import Profile
class ProfileImageForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image']
'WHAT I LEARN > TIL' 카테고리의 다른 글
[TIL][240829] RESTful API, DRF 기초 (0) | 2024.08.29 |
---|---|
[TIL][240823] HTML 드롭다운 선택 문제 해결 (0) | 2024.08.23 |
[TIL][240821] fork 복습 (0) | 2024.08.21 |
[TIL][240820] Bootstrap - Grid system (0) | 2024.08.20 |
[TIL][240819] Overriding (0) | 2024.08.19 |