class LoginForm(forms.Form):
username = forms.CharField(
error_messages={
'required': '아이디를 입력해주세요.'
},
max_length=32, label='사용자 이름')
password = forms.CharField(
error_messages={
'required': '비밀번호를 입력해주세요.'
},
widget=forms.PasswordInput, label='비밀번호')
def clean(self):
# super()는 메소드 오버라이딩
cleaned_data = super().clean() # 값이 들어있는지 검사한다. 들어잇으면 아래 변수를 할당, 없으면 실패하고 튕군다.
username = cleaned_data.get('username')
password = cleaned_data.get('password')
if username and password:
# 미등록 아이디를 치면 에러를 추가한다.
try:
fcuser = Fcuser.objects.get(username=username)
except Fcuser.DoesNotExist:
self.add_error('username', '등록되지 않은 아이디입니다.')
return
if not check_password(password, fcuser.password):
self.add_error('password', '비밀번호를 틀렸습니다.')
else:
self.user_id = fcuser.id
def board_detail(request, pk):
try:
board = Board.objects.get(pk=pk)
except Board.DoesNotExist:
raise Http404('게시글을 찾을 수 없습니다.')
return render(request, 'board_detail.html', {'board':board})
url접속시 등록되지 않은 질문의 pk로 접속하면 에러페이지로 이동한다.
def board_write(request):
### session이 없으면 로그인 페이지로 이동시킨다.
if not request.session.get('user'):
return redirect('/fcuser/login/')
if request.method == 'POST':
form = BoardForm(request.POST)
if form.is_valid():
user_id = request.session.get('user')
fcuser = Fcuser.objects.get(pk=user_id)
board = Board()
board.title = form.cleaned_data['title']
board.contents = form.cleaned_data['contents']
board.writer = fcuser
board.save()
return redirect('/board/list')
else:
form = BoardForm()
return render(request, 'board_write.html', {'form': form})