Django 에서 회원가입 기능을 구현하기 위해 UserCreationForm 을 사용할 수 있다.
Django의 UserCreationForm 클래스는 django.contrib.auth.form 패키지에 있으며, 이를 상속해서 유저 생성 form 을 쉽게 구현할 수 있다.
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class UserForm(UserCreationForm):
email = forms.EmailField(label="email")
# 장고 모델 폼은 내부 클래스로 Meta 클래스를 가져야 하며, Meta 클래스에는 모델폼이 사용할 모델, 필드 작성이 필요
class Meta:
model = User
fields = ("username", "email")
그러다가 UserCreationForm 클래스 내부가 궁금해서 공식 Django docs를 찾아보았다
https://docs.djangoproject.com/en/1.8/_modules/django/contrib/auth/forms/
Django
The web framework for perfectionists with deadlines.
docs.djangoproject.com
내가 백엔드 프레임워크는 Django 밖에 안써봐서 비교를 못하고 있는데 원래 이렇게 기능 구현이 간편해도 되는걸까..???? ㅎㅎ...
Django는 편리한 기능이 많아서 빠르게 개발할때 도움이 되는 것 같다
Django는 우리가 여느 웹사이트에서나 흔히 볼 수 있었던 회원가입 기능을 이렇게 제공해주고 있다. 그리고 우리는 이걸 날먹...
class UserCreationForm(forms.ModelForm):
"""
A form that creates a user, with no privileges, from the given username and
password.
"""
error_messages = {
'password_mismatch': _("The two password fields didn't match."),
}
password1 = forms.CharField(label=_("Password"),
widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"),
widget=forms.PasswordInput,
help_text=_("Enter the same password as above, for verification."))
# forms.ModelForm 을 상속 받으므로, Meta class를 생성해준다
class Meta:
model = User
fields = ("username",)
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
# error handling
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)
return password2
# 생성한 user 객체를 저장하는 메서드
def save(self, commit=True):
# user 객체에 대한 정보가 아직 다 안들어 왔으므로 commit = False
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
password1 에 사용자 패스워드를 입력하게하고, password2로 비밀번호 재입력을 받는다. 그리고 password1 != password2 일때 error message를 보내는 방식으로 에러 핸들링을 하고 있다.
save() 함수로 생성한 사용자 객체를 저장한다. 새로 생성된 사용자 객체는 데이터베이스 혹은 admin 페이지에서 확인할 수 있다.
'Backend > Django' 카테고리의 다른 글
[Django] 장고 앱에서 CORS 설정하기 (1) | 2023.11.19 |
---|