from django.contrib.auth.forms import UserCreationForm
@require_http_method(['GET','POST'])
def signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save() # UserCreationForm이 user를 return 하기때문에 가능
auth_login(request, user)
return redirect('articles:index')
else:
form = UserCreationForm()
context = {
'form' : form,
}
return render(request, 'accounts/signup.html', context)
< UserCreationForm의 save 메서드 >
from django.views.decorators.http import require_POST
@require_POST
def delete(request):
if request.user.is_authenticated:
request.user.delete()
auth_logout(request) # session 지우기. 단 탈퇴후 로그아웃순으로 처리. 먼저 로그아웃하면 해당 request 객체 정보가 없어져서 삭제가 안됨.
return redirect('articles:index')
from django.contrib.auth.forms import UserChangeForm
def update(request):
if request.method == "POST":
pass
else:
form = UserChangeForm(instance=request.user)
context = {
'form' : form,
}
return render(request, 'accounts/update.html', context)
forms.py
파일 만들기
# forms.py
from django.contrib.auth.forms import UserChangeForm
from django.contrib.auth import get_user_model
class CustommUserChangeForm(UserChangeForm):
class Meta:
model = get_user_model()
fields = ('email', 'first_name', 'last_name')
# views.py
from .forms import CustomUserChangeForm
@login_required
@require_http_methods(['GET','POST'])
def update(request):
if request.method == 'POST':
form = CustomUserChangeForm(request.POST, instance=request.usr)
if form.is_valid():
form.save()
return redirect('articles:index')
else:
form = CustomUserChangeForm(instance=request.user)
context = {
'form':form,
}
return render(request, 'accounts/update.html', context)
https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#referencing-the-user-model
from django.contrib.auth.forms import PasswordChangeForm
def change_password(request):
if request.method == 'POST':
form = PasswordChangeForm(request.user, request.POST)
if form.is_valid():
form.save()
return redirect('articles:index')
else:
form = PasswordChangeForm(request.user)
context = {
'form' : form,
}
return render(request, 'articles/change_password.html, context)
# 위와 같은 상황에서 비밀번호를 바꾸면 로그아웃이 되어버림. 사용자 정보고 바뀌었기 때문에
# views.py
from django.contirb.auth import update_session_auth_hash
@login_required
def change_password(request):
if request.method == 'POST':
form = PasswordChangeForm(request.user, request.POST)
if form.is_valid():
form.save()
update_session_auth_has(request, form.user)
return redirect('articles:index')
else:
form = PasswordChangeForm(request.user)
context = {
'form' : form,
}
return render(request, 'articles/change_password.html, context)