파이썬 인강 자기계발 챌린지 32회차 미션
1. 비밀번호와 비밀번호확인값 데이터베이스에 넣기
원래 프론트앤드에서 주로 담당하지만 백엔드로도 만들 수 있다.
기본 코드는 앱 하위 view.py파일에서 아래 코드를 작성한다.
- request를 가져오는 방식에느 get과 post가 있다.
- post일때 회원가입페이지이므로
register.html
파일에서 input태그마다 붙여준 name값을 키로 가지고와서 함수를 실행시킨다.
- fcuser에 입력값을 생성하기 위해서는 기존의 clas fcuser를 상단에 import해야한다 ->
from .models import Fcuser
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| from django.shortcuts import render from .models import Fcuser
def register(request): if request.method == "GET": return render(request, 'register.html') elif request.method == "POST": username = request.POST['username'] password = request.POST['password'] re_password = request.POST['re-password'] fcuser = Fcuser( username=username, password=password )
fcuser.save()
return render(request, 'register.html')
|

회원가입페이지에서 값들을 입력하고 등록버튼을 누르면 빤짝하고 아래 이미지처럼 모든 값들이 리셋되어진다.

어떠한 변화가 생긴걸까?
위의 코드의 함수가 실행되었지만 입력값들이 post로 들어왔기때문에 elif문을 실행해주고 마지막에 render가 ‘register.html’를 호출했기때문에 페이지사의 변화는 없어보일뿐 데이터는 데이터베이스에 저장되어있다.
2. 비밀번호와 비밀번호확인입력값이 일치하는 지 확인
일치여부는 if문으로 간단하게 나타낼수있다.
앱 하위의 views.py에서 아래 코드를 작성하면된다
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| from django.shortcuts import render from .models import Fcuser from django.http import HttpResponse
def register(request): if request.method == "GET": return render(request, 'register.html') elif request.method == "POST": username = request.POST['username'] password = request.POST['password'] re_password = request.POST['re-password'] if password != re_password: return HttpResponse('비밀번호가 다릅니다')
fcuser = Fcuser( username=username, password=password )
fcuser.save()
return render(request, 'register.html')
|

기존이 회원가입페이지내용이 다 사라져버려서 유저입장에서 불편하다.
따라서 기존 코드에서 더 나아가보자.
기존 register()함수에서 res_data = {}
변수를 생성하여 불일치의 경우의 데이터를 변수에 담는다.
함수가 끝나가는 마지막라인에서 변수 res_data도 함께 return해준다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| def register(request): if request.method == "GET": return render(request, 'register.html') elif request.method == "POST":
username = request.POST['username'] password = request.POST['password'] re_password = request.POST['re-password'] res_data = {} if password != re_password: res_data['error'] = '비밀번호가 다릅니다'
fcuser = Fcuser( username=username, password=password )
fcuser.save()
return render(request, 'register.html', res_data)
|
위 코드이 변수res_data가 return할 값이 출력되어야하기때문에 register.html
error가 출력된 수 있도록 코드를 추가해야한다.
에러코드가 나타나길 원하는 위치에 {{ error }}를 작성해주면 끝!
1 2 3 4 5
| <div class="row"> <div class="col-12"> {{ error }} </div> </div>
|
