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 ๋ฐ์ ์์จ๋ด์ ๋น๊ต๋ฅผ ๋ชปํ๊ณ ์๋๋ฐ ์๋ ์ด๋ ๊ฒ ๊ธฐ๋ฅ ๊ตฌํ์ด ๊ฐํธํด๋ ๋๋๊ฑธ๊น..???? ใ ใ ...
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 |
---|