Django - Sign up

문주은·2022년 5월 5일
0

django

목록 보기
1/1

1. app 추가

$ 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')
]
  • view가 생길때마다 url 등록

🖥 app/urls.py path 등록

from django.urls import path
from . import views

urlpatterns = [
    path('signup/', views.signup, name='signup')
]

2. 회원가입

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})
  • customuser를 사용해 django에서 제공되는 개인 정보 외에 다른 정보도 받아 올 수 있도록 한다.

🖥 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 %}
  • blob content ~ endblock 까지의 내용을 base.html에 sign up 파트에 해당하는 부분만 넣기 위한 html

3. 로그인

🖥 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")
  • render :
  • redirect :

🖥 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>
profile
Data Engineer

0개의 댓글