유저 커스텀 모델을 이용하니 에러 form.errors 가 사용 불가한데 해결방법이 있을까요
{% extends "base.html" %}
{% block content %}
<div class="container my-3">
<div class="row">
<div class="">
<h4>로그인</h4>
</div>
</div>
<form method="post" class="post-form" action="{% url 'users:login' %}">
{% csrf_token %}
<input type="hidden" name="next" value="{{ next }}">
<div class="form-group">
<label for="email">EMAIL</label>
<input type="text" class="form-control {% if form.errors %} is-invalid {% endif %}" name="username" id="username"
value="{{ form.email.value|default_if_none:'' }}">
</div>
<div class="form-group">
<label for="password">PASSWORD</label>
<input type="password" class="form-control{% if form.errors %} is-invalid {% endif %}" name="password" id="password"
value="{{ form.password.value|default_if_none:'' }}">
{% include "form_errors.html" %}
</div>
<button type="submit" class="btn btn-primary">로그인</button>
<button type="button" class="btn btn-primary" >
<a style="color: darkgray" href="{% url 'users:signup' %}">회원가입</a>
</button>
</form>
</div>
{% endblock %}
{% for field in form %} <!-- 필드 오류 출력 -->
{% for error in field.errors %}
<div class="invalid-feedback">
<strong>{{ field.label }}</strong>은 {{ error }}
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %} <!-- 넌필드 오류 출력 -->
<div class="invalid-feedback">
<strong>{{ error }}</strong>
</div>
{% endfor %}
책과 똑같이 작성한 로그인 페이지일 경우 정상적으로 오류 메시지가 출력됩니다
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class MyAccountManager(BaseUserManager):
def create_user(self, email, username, password=None):
if not email:
raise ValueError("올바른 이메일을 입력해주세요")
if not username:
raise ValueError("올바른 닉네임을 입력해주세요")
user = self.model(
email=self.normalize_email(email),
username=username,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password):
user = self.create_user(
email=self.normalize_email(email),
password=password,
username=username,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class Account(AbstractBaseUser):
email = models.EmailField(verbose_name="email", max_length=80, unique=True)
username = models.CharField(max_length=30, unique=True)
birth_date = models.DateField(blank=True, null=True)
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', ]
object = MyAccountManager()
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
from django import forms
from django.contrib.auth.forms import UserCreationForm
from users.models import Account
class SignupForm(UserCreationForm):
email = forms.EmailField(max_length=60)
class Meta:
model = Account
fields = ('email', 'username', 'password1', 'password2')
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from users.forms import SignupForm
def signup(request):
"""
회원가입
"""
context = {}
if request.method == "POST":
form = SignupForm(request.POST)
if form.is_valid():
form.save()
email = form.cleaned_data.get('email')
raw_password = form.cleaned_data.get('password1')
account = authenticate(email=email, password=raw_password)
login(request, account)
return redirect('list')
else:
context['signupForm'] = form
else:
form = SignupForm()
context['signupForm'] = form
return render(request, 'users/signup.html', context)
from django.contrib.auth import views as auth_views
from django.urls import path
from .import views
app_name = 'users'
urlpatterns = [
path('login/', auth_views.LoginView.as_view(
template_name='users/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
path('signup/', views.signup, name='signup'),
]
{% extends "base.html" %}
{% block content %}
<div class="container my-3">
<div class="row my-3">
<div class="col-4">
<h4>회원가입</h4>
</div>
<div class="col-8 text-right">
<span> 또는 <a href="{% url 'users:login' %}">로그인</a>하세요 </span>
</div>
</div>
<form method="post" class="post-form">
{% csrf_token %}
<div class="form-group">
<label for="email">이메일</label>
<input type="text" class="form-control {% if form.errors.email %} is-invalid {% endif %}" name="email" id="email"
value="{{ form.email.value|default_if_none:'' }}" >
</div>
<div class="form-group">
<label for="username">닉네임</label>
<input type="text" class="form-control {% if form.errors.username %} is-invalid {% endif %}" name="username" id="username"
value="{{ form.username.value|default_if_none:'' }}" >
</div>
<div class="form-group">
<label for="password1">비밀번호</label>
<input type="password" class="form-control {% if form.errors.password1 %} is-invalid {% endif %}" name="password1" id="password1"
value="{{ form.password1.value|default_if_none:'' }}" >
</div>
<div class="form-group">
<label for="password2">비밀번호 확인</label>
<input type="password" class="form-control {% if form.errors.password2 %} is-invalid {% endif %}" name="password2" id="password2"
value="{{ form.password2.value|default_if_none:'' }}" >
{% include "form_errors.html" %}
</div>
<button type="submit" class="btn btn-primary">생성하기</button>
</form>
</div>
{% endblock %}
회원가입 페이지는 오류메시지가 출력되지 않내요...
유저 모델 커스텀 전에는 출력 되었는데 지금은 안되내요 해결방법이 있을까요?
123 님 791
2021년 3월 26일 10:19 오후