Django PreCourse 3-2) User Model and Registration

Turtle·2023년 12월 21일
0
post-thumbnail

📌django.contrib.auth

  • 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.

    참고 자료 - Django django.contrib.auth

📌적용

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(username, email=None, password=None, **extra_fields)

  • create_user는 사용자를 생성, 저장 및 반환한다.
  • 사용자 이름과 비밀번호는 주어진 대로 설정된다. 이메일의 도메인 부분은 자동으로 소문자로 변환되고 변환된 User 개체에는 is_active가 True로 설정된다.
  • 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()

📌Cleaning and validating fields that depend on each other

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()을 호출하면 부모 클래스의 모든 유효성 검사 로직이 유지된다.

📌Raising ValidationError

raise forms.ValidationError({"re_password" : "2개의 비밀번호 필드가 일치하지 않습니다."})
  • Django에서는 기본적으로 에러 메시지가 영어로 출력이 되는데 이를 한글로도 출력이 가능하도록 할 수 있다.
  • 폼에서 생성한 필드명을 Key값으로 두고 Value값을 한글 에러 메시지로 작성하게 되면 ValidationError발생 시에 에러 메시지가 한글로 출력이 된다.

📌Specifying custom error messages

  • error_messages 인수를 사용하면 필드에서 발생하는 Django의 기본 메시지를 무시할 수 있다. 이 때, error_messages를 작성할 때, Key-Value구조로 작성해야한다.
  • 어떤 필드를 사용하느냐에 따라서 error_messagesKey값에 들어가는 에러 메시지의 유형을 결정할 수 있는데 예를 들어 아래와 같은 코드에서 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

0개의 댓글