패스트캠퍼스 파이썬 웹개발 올인원 패키지 후기(34)
파이썬 웹개발 올인원 패키지 34 일차 후기 겸 학습기록 입니다.
게시판 만들기 - 1

board_list.html
{% extends "base.html" %}
{% block contents %}
<div class='row mt-5'>
<div class='col-12'>
<table class='table table-light'>
<thead class='thead-light'>
<tr>
<th>#</th>
<th>제목</th>
<th>아이디</th>
<th>일시</th>
</tr>
</thead>
<tbody class='text-dark'>
{% for board in boards %}
<tr>
<th>{{ boar.id }}</th>
<td>{{ board.title }}</td>
<td>{{ board.writer }}</td>
<td>{{ board.registered_dttm}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<div class='row'>
<div class='col-12'>
<button clas='btn btn-primary'>글쓰기</button>
</div>
</div>
{% endblock %}
fc_community/urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('fcuser/', include('fcuser.urls')),
path('board/', include('board.urls')),
path('', home),
]
board/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('list/', views.board_list),
]
views.py
from django.shortcuts import render
from .models import Board
# Create your views here.
def board_list(request):
boards = Board.objects.all().order_by('-id')
return render(request, 'board_list.html', {'boards': boards})
models.py
from django.db import models
# Create your models here.
class Board(models.Model):
title = models.CharField(max_length=128, verbose_name="제목")
contents = models.TextField(verbose_name="내용")
writer = models.ForeignKey('fcuser.Fcuser', on_delete=models.CASCADE, verbose_name="작성자")
registered_dttm = models.DateTimeField(auto_now_add=True, verbose_name="등록시간")
def __str__(self):
return self.title
class Meta:
db_table = 'fastcampus_board'
verbose_name = '패스트캠퍼스 게시글'
verbose_name_plural = '패스트캠퍼스 게시글'
admin.py
from django.contrib import admin
from .models import Board
class BoardAdmin(admin.ModelAdmin):
list_display = ('title',)
admin.site.register(Board, BoardAdmin)
게시판 만들기 - 2

board_write.html
{% extends "base.html" %}
{% block contents %}
<div class='row mt-5'>
<div class='col-12'>
<form method="POST" action=".">
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<label for="{{ filed.id_for_label }}">{{ field.label }}</label>
{% ifequal field.name 'contents' %}
<textarea class='form-control' name='{{ field.name }}' placeholder="{{ field.label }}"></textarea>
{% else %}
<input type="{{ field.field.widget.input_type }}" class="form-control" id="{{ filed.id_for_label }}" placeholder="{{ field.label }}" name="{{ field.name }}" />
{% endifequal %}
</div>
{% if field.errors %}
<span style="color: red">{{ field.errors }}</span>
{% endif %}
{% endfor %}
<button type="submit" class="btn btn-primary">글쓰기</button>
</form>
</div>
</div>
{% endblock %}
board_detail.html
{% extends "base.html" %}
{% block contents %}
<div class='row mt-5'>
<div class='col-12'>
<div class="form-group">
<label for="title">제목</label>
<input type="text" class="form-control" id="title" value='{{ board.title }}' readonly />
<label for="contents">내용</label>
<textarea class='form-control' readonly>{{ board.contents }}</textarea>
</div>
<button class="btn btn-primary">돌아가기</button>
</div>
</div>
{% endblock %}
views.py
## 생략 ##
def board_detail(request, pk):
board = Board.objects.get(pk=pk)
return render(request, 'board_detail.html', {'board': board})
def board_write(request):
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})
## 생략 ##
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('detail/<int:pk>/', views.board_detail),
path('list/', views.board_list),
path('write/', views.board_write),
]
forms.py
from django import forms
class BoardForm(forms.Form):
title = forms.CharField(max_length=128, label="제목", error_messages={'required': '제목 입력해주세요.'})
contents = forms.CharField(widget=forms.Textarea, label="내용", error_messages={'required': '내용을 입력해주세요.'})
게시판 만들기 - 3 (예외처리)

로그인 예외처리(존재하지 않는 아이디 입력시)
forms.py
from django import forms
from .models import Fcuser
from django.contrib.auth.hashers import check_password
class LoginForm(forms.Form):
username = forms.CharField(max_length=64, label="사용자 이름", error_messages={'required': '아이디를 입력해주세요.'})
password = forms.CharField(widget=forms.PasswordInput, label="비밀번호", error_messages={'required': '비밀번호를 입력해주세요.'})
def clean(self):
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
글 상세 보기 및 글 쓰기 예외처리(없는 글 조회 또는 로그인 하지 않은 사용자가 글쓰기 할때 로그인 페이지로 리다이렉트 처리)
views.py
from django.shortcuts import render, redirect
from fcuser.models import Fcuser
from .models import Board
from .forms import BoardForm
from django.http import Http404
# Create your views here.
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})
def board_write(request):
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})
def board_list(request):
boards = Board.objects.all().order_by('-id')
return render(request, 'board_list.html', {'boards': boards})
패스트캠퍼스 파이썬 인강 자세한 내용은 아래 링크를 참고해 주세요!
'Django Basics' 카테고리의 다른 글
| [패스트캠퍼스 수강 후기] 파이썬 인강 자기계발 챌린지 35 회차 미션 (0) | 2020.06.28 |
|---|---|
| [패스트캠퍼스 수강 후기] 파이썬 인강 자기계발 챌린지 33 회차 미션 (0) | 2020.06.26 |
| [패스트캠퍼스 수강 후기] 파이썬 인강 자기계발 챌린지 32 회차 미션 (0) | 2020.06.25 |
| [패스트캠퍼스 수강 후기] 파이썬 인강 자기계발 챌린지 31 회차 미션 (0) | 2020.06.24 |
| [패스트캠퍼스 수강 후기] 파이썬 인강 자기계발 챌린지 30 회차 미션 (1) | 2020.06.23 |