$ python manage.py startapp account
: 'account'이름의 app 추가
🖥 settings.py app추가
INSTALLED_APPS = [
... ,
'account',
'bootstrap4'
]
🖥 project/urls.py 등록
app_name = 'appname'
urlpatterns = [
path('admin/', admin.site.urls),
path('signup', views.signup, name='signup'),
path('login', views.login, name='login')
]
🖥 app/urls.py path 등록
from django.urls import path
from . import views
urlpatterns = [
path('signup/', views.signup, name='signup')
]
signup은 request 받은 password1(회원가입할 비밀번호)와 password2(비밀번호 확인)가 같을 경우에만 회원가입이 진행
🖥 회원가입 views.py
from django.shortcuts import render, redirect
from django.contrib import auth
from django.contrib.auth.models import User
from .forms import CustomUserCreationForm, CustomUserChangeForm
# 회원가입 views
@csrf_exempt
def signup(request):
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('appname:home')
else:
form = CustomUserCreationForm()
return render(request, 'appname/signup.html', {'form': form})
🖥 forms.py
from django.contrib.auth.forms import UserChangeForm, UserCreationForm, ReadOnlyPasswordHashField
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = CustomUser
fields = ('username', 'email') # <- User 생성시 보여줄 field 을 정의한다.
🖥 signup.html
{% block content %}
<h2>Sign Up</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Sign Up</button>
</form>
{% endblock %}
🖥 views.py
@csrf_exempt
def login(request):
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(
request, username=username, password=password
)
if user is not None:
login(request, user)
return redirect('appname:home')
else:
return render(request, "appname/login.html", {
'error': 'Username or Password is incorrect.',
})
else:
if request.user.is_authenticated:
return redirect('appname:home')
else:
return render(request, "appname/login.html")
🖥 login.html
<form action="{% url 'appname:login' %}" method="post">
{% csrf_token %}
<div class="form-group">
<label>Username</label>
<input type="text" placeholder="Enter usrename" name="username">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" placeholder="Enter password" name="password">
</div>
<div class="form-group">
<button type="submit">Login</button>
</div>
</form>