ㅤㅤㅤㅤㅤ○ 사용할 수 있는 기능 및 설명서 ○
1. Accounts - Profile
Profile - views
유저의 프로필 (찾아 오시는 길)
- 프로필 기본 로직
<div id="profile-container">
<div class="profile-image">
<img id="profile-picture" alt="Profile Picture">
</div>
<div class="profile-text">
<p id='text'>닉네임 <span id="nickname"></span></p>
<div class="profile-a">
<a href="#" id="edit-profile-button">프로필 수정</a>
</div>
</div>
</div>
프로필 수정
Profile_update
프로필을 수정을 하고 싶다면? 여기서! 하면 된다~(내 프로필 정보를 Load해서 내 정보를 잊어 버릴 걱정은 없다)
username(이름)은 = ID이다
1.document.getElementById('update-profile-form').addEventListener('submit', function(event) {
event.preventDefault();
2.const formData = new FormData();
3.formData.append('username', document.getElementById('username').value);
formData.append('nickname', document.getElementById('nickname').value);
formData.append('email', document.getElementById('email').value);
4.const imageFile = document.getElementById('image').files[0];
if (imageFile) {
formData.append('image', imageFile);
}
① update-profile-form 폼 요소에 이벤트 리스너를 추가
② 키-값 쌍으로 폼 데이터를 저장
③ 입력 필드 값
④ 프로필에 이미지가 존재할 경우, 수정 프로필에 객체 이미지를 추가
document.getElementById('change-password-form').addEventListener('submit', function(event) {
event.preventDefault();
const data = {
1.current_password: document.getElementById('current_password').value,
2.new_password: document.getElementById('new_password').value
};
비밀 번호 변경
① 현재 비밀번호를 입력 필드에서 가져와 객체에 추가
② 새 비밀번호를 입력 필드에서 가져와 객체에 추가
2. Posts - comments
댓글 수정
async function editComment(commentId, currentContent) {
const newContent = prompt("새로운 댓글 내용을 입력하세요:", currentContent);
if (newContent === null) {
return;
}
const csrfToken = getCsrfToken();
const access = window.localStorage.getItem('access');
const formData = new FormData();
formData.append('content', newContent);
try {
await axios.put(`/api/posts/api/comments/${commentId}/`, formData, {
headers: {
'Authorization': `Bearer ${access}`,
'X-CSRFToken': csrfToken //
}
});
window.location.reload(); //
} catch (error) {
console.error('댓글 수정 실패:', error);
}
}
const access = window.localStorage.getItem('access')
로컬 스토리지에서 액세스 토큰을 가져옴
댓글 삭제!
function deleteComment(commentId) {
if (!confirm("댓글을 삭제하시겠습니까?")) {
return;
}
const csrfToken = getCsrfToken();
axios.delete(`/api/posts/api/comments/${commentId}/`, {
headers: {
'X-CSRFToken': csrfToken
}
})
.then(response => {
window.location.reload();
})
.catch(error => {
console.error('댓글 삭제 실패.', error);
});
}
.then(response => { window.location.reload();
댓글 삭제후 재시작
axios.delete(`/api/posts/api/comments/${commentId}/`, { headers: { 'X-CSRFToken': csrfToken
댓글 삭제 토큰추가
3. Email - Authentication
회원가입시 이메일 인증
def perform_create(self, serializer):
user = serializer.save()
user.is_active = False
user.save()
self.send_verification_email(user)
def send_verification_email(self, user):
token = default_token_generator.make_token(user)
uid = urlsafe_base64_encode(force_bytes(user.pk))
subject = '이메일 인증 요청'
message = render_to_string('accounts/email_verification.html', {
'user': user,
'uid': uid,
'token': token,
'protocol': 'http',
'domain': 'your-domain.com'
})
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [user.email])
user.is
_active = False
이메일 인증을 안하면 로그인 못하게 적용
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [
user.email
])
유저의 이메일로 발송
이메일 인증 API
class VerifyEmailView(APIView):
permission_classes = [AllowAny]
def get(self, request, uidb64, token):
try:
uid = urlsafe_base64_decode(uidb64).decode()
user = get_user_model().objects.get(pk=uid)
except (TypeError, ValueError, OverflowError, get_user_model().DoesNotExist):
user = None
if user is not None and default_token_generator.check_token(user, token):
user.is_active = True
user.save()
return Response({'message': '이메일 인증이 완료되었습니다.'}, status=status.HTTP_200_OK)
urlsafe_base64_decode(uidb64).decode()
URL-safe base64로 인코딩된 uidb64
를 디코딩하여 사용자 ID를 얻는다get_user_model().objects.get(pk=uid)
: 디코딩된 사용자 ID를 이용해 데이터베이스에서 해당 사용자를 조회.
if user is not None and default_token_generator.check_token(user, token)
사용자 토큰검사
이메일 재발급 요청
def post(self, request):
email = request.data.get('email') # 요청에서 이메일을 가져옴
user = get_object_or_404(get_user_model(), email=email)
SignUpView().send_verification_email(user)
return Response({'message': '이메일 인증 메일이 재발송되었습니다.'}, status=status.HTTP_200_OK)
SignUpView().send_verification_email(user)
이메일 재발송!
SMTP 설정
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = '************'
EMAIL_BACKEND
이메일을 보내기 위한 사용할 백엔드EMAIL_HOST
이메일을 보내기 위한 SMTP서버EMAIL_USE_TLS
TLS를 사용하여 이메일을 보낼지 선택 (TLS란?)EMAIL_HOST_USER
인증을 위해 메일을 보낼 때 사용할 이메일