Django의 Authentication(인증) 기능을 구현하기 위해서 django.contrib.auth.models import User
를 사용하는데 기본 필드는 아래와 같이 구성되어있다.
username : Required. 150 characters or fewer. Usernames may contain alphanumeric, _, @, +, . and - characters.
first_name : Optional (blank=True). 150 characters or fewer.
last_name : Optional (blank=True). 150 characters or fewer.
email : Optional (blank=True). Email address.
password : Required. A hash of, and metadata about, the password. (Django doesn’t store the raw password.) Raw passwords can be arbitrarily long and can contain any character. See the password documentation.
groups : Many-to-many relationship to Group
user_permissions : Many-to-many relationship to Permission
is_staff : Boolean. Allows this user to access the admin site.
is_active : Boolean. Marks this user account as active. We recommend that you set this flag to False instead of deleting accounts. That way, if your applications have any foreign keys to users, the foreign keys won’t break.
is_superuser : Boolean. Treats this user as having all permissions without assigning any permission to it in particular.
last_login : A datetime of the user’s last login.
date_joined : The date/time when the account was created.
from django import forms
from .models import Application
class RegisterForm(forms.Form):
email = forms.EmailField(label="이메일", error_messages={'invalid' : '이메일 형식이 올바르지 않습니다.',})
password = forms.CharField(label="1차 비밀번호", min_length=6, max_length=20, widget=forms.PasswordInput)
re_password = forms.CharField(label="2차 비밀번호", min_length=6, max_length=20, widget=forms.PasswordInput)
def clean(self):
cleaned_data = super(RegisterForm, self).clean()
password = cleaned_data['password']
re_password = cleaned_data['re_password']
if password and re_password:
if password != re_password:
raise forms.ValidationError({"re_password" : "2개의 비밀번호 필드가 일치하지 않습니다."})
return cleaned_data
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.models import User
from django.contrib import auth
from django.contrib import messages
from .forms import RegisterForm, LoginForm, ApplicationForm
from django.db.models import ObjectDoesNotExist
from .models import Application
def register(request):
if request.method == "POST":
form = RegisterForm(request.POST)
if form.is_valid():
email = form.cleaned_data['email']
password = form.cleaned_data['password']
User.objects.create_user(email, email, password)
return HttpResponseRedirect('/')
else:
form = RegisterForm()
context = {
'form' : form,
}
return render(request, 'Myapp/register.html', context)
create_user
는 사용자를 생성, 저장 및 반환한다.create_user
의 첫 번째 인자에는 username, 두 번째 인자에는 email, 세 번째 인자에는 password가 들어간다.>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user("john", "lennon@thebeatles.com", "johnpassword")
# At this point, user is a User object that has already been saved
# to the database. You can continue to change its attributes
# if you want to change other fields.
>>> user.last_name = "Lennon"
>>> user.save()
def clean(self):
cleaned_data = super(RegisterForm, self).clean()
password = cleaned_data['password']
re_password = cleaned_data['re_password']
if password and re_password:
if password != re_password:
raise forms.ValidationError({"re_password" : "2개의 비밀번호 필드가 일치하지 않습니다."})
return cleaned_data
super(RegisterForm, self).clean()
을 호출하면 부모 클래스의 모든 유효성 검사 로직이 유지된다.raise forms.ValidationError({"re_password" : "2개의 비밀번호 필드가 일치하지 않습니다."})
Key
값으로 두고 Value
값을 한글 에러 메시지로 작성하게 되면 ValidationError
발생 시에 에러 메시지가 한글로 출력이 된다.error_messages
인수를 사용하면 필드에서 발생하는 Django의 기본 메시지를 무시할 수 있다. 이 때, error_messages
를 작성할 때, Key-Value
구조로 작성해야한다.error_messages
의 Key
값에 들어가는 에러 메시지의 유형을 결정할 수 있는데 예를 들어 아래와 같은 코드에서 CharField
의 경우 들어갈 수 있는 유형은 required(필수)
, max_length(최대 길이)
, min_length(최소 길이)
등이 들어갈 수 있다.>>> name = forms.CharField(error_messages={"required": "Please enter your name"})
>>> name.clean("")
Traceback (most recent call last):
...
ValidationError: ['Please enter your name']
참고 자료 - Django Specifying Custom error messages
참고 자료 - Django StackOverflow