📌 views.py - board
from django.shortcuts import render
from .models import Board #현재 폴더의 models.py
from django.utils import timezone
from django.http import HttpResponseRedirect
from django.core.paginator import Paginator
# Create your views here.
def write(request) : # 게시판 등록
if request.method != "POST" :
return render(request,"board/write.html")
else : #POST 방식 요청
try : # 첨부파일이 있는 경우
filename = request.FILES["file1"].name # 업로드 파일의 이름
# request.FILES["file1"] : 업로드 된 파일의 내용
handle_upload(request.FILES["file1"])
except : # 업로드 되는 파일이 없는 경우
filename = ""
#num : 자동으로 1이 증가함.(maria db의 기능)
b=Board(name=request.POST["name"],\\
pass1=request.POST["pass"],\\
subject=request.POST["subject"],\\
content=request.POST["content"],\\
regdate=timezone.now(),\\
readcnt=0,file1=filename)
b.save() # db에 b객체의 값이 저장. insert실행. num 기본키값이 새 값으로 생성하기 때문에.
return HttpResponseRedirect("../list") # 목록보기
def handle_upload(f) :
# 파일 업로드 위치 : BASE_DIR/file/board/폴더
# f.name : 업로드 파일의 이름
with open("file/board/"+f.name,"wb") as dest :
# f.chunks : 업로드 되는 파일에서 버퍼만큼 읽기
for ch in f.chunks() :
dest.write(ch) # 출력파일에 저장
# 게시물 목록보기
def list(request) :
# pageNum 파라미터를 정수형으로 변환.
# 파라미터가 없으면 1이 기본값.
pageNum = int(request.GET.get("pageNum",1))
#모든 레코드 조회.
# order_by("-num") : num 값의 내림차순 정렬.
# all_boards : 등록된 전체 게시물 목록
all_boards = Board.objects.all().order_by("-num")
#Paginator : all_boards 목록을 10개씩 묶어 분리 저장.
paginator = Paginator(all_boards,10)
#paginator 객체에서 pageNum 번째 게시물 리턴
#board_list : 페이지에 출력할 게시물 목록 저장
board_list = paginator.get_page(pageNum)
#등록된 게시물 건수
listcount = Board.objects.count()
return render(request,"board/list.html",\\
{"board":board_list,"listcount":listcount})
# num : 화면에서 요청한 게시물 번호.
# url에 표시된 게시물 번호.
def info(request,num) :
board = Board.objects.get(num=num) # num 값에 해당하는 게시물 한개 저장
board.readcnt += 1 # 조회건수값1 증가
board.save() # db에 조회건수 저장
return render(request,"board/info.html",{"b":board})
📌 list.py
{% extends "base1.html" %}
{% block content %}
<table border="1" width="100%" cellpadding="0" cellspacing="0"
class="table table-bordered table-hover">
<tr align="center">
<td colspan="4">장고 게시판</td>
{% if listcount == 0 %}
<td align="center">등록된 글이 없습니다.</td>
{% else %} {# 등록된 게시물이 존재하는 경우 #}
<td align="center">글개수 :{{listcount}}</td>
</tr>
<tr align="center" valign="middle">
<td width="8%">번호</td><td width="50%">제목</td>
<td width="14%">작성자</td><td width="17%">날짜</td>
<td width="11%">조회수</td></tr>
{% for bo in board %} {# 게시글 출력 : bo : 게시물 한개 저장 #}
<tr align="center" valign="middle">
<td>{{bo.num}}</td><td align="left">
{# 첨부 파일이 존재하면 @로 표시함 #}
{% if bo.file1 %}
<a href="/file/board/{{bo.file1}}">@</a>
{% else %} {# 첨부 파일이 없는 경우 공백 표시함 #}
{% endif %}
{# 첨부 파일 표시 종료 #}
<a href="../info/{{bo.num}}/">{{bo.subject}}</a></td>
<td>{{bo.name}}</td><td>{{bo.regdate}}</td>
<td>{{bo.readcnt}}</td></tr>
{% endfor %}
<!-- Pagination -->
<tr><td colspan="5" style="text-align:center">
<div class="pagination">
<div style="width:35%; margin: 5px; display:inline">
{% if board.has_previous %} {# 앞 페이지가 존재? #}
<a class="abutton" href="?pageNum=1">맨 앞으로</a>
<a class="abutton" href="?pageNum={{ board.previous_page_number }}">이전</a>
{% endif %}
</div>
<div style="width:30%; margin: 5px; display:inline">
{# board.paginator.page_range : 전체 제공된 페이지 번호#}
{% for page in board.paginator.page_range %}
{# 현재 페이지 번호를 포함해서 5개씩만 페이지 번호를 표시 #}
{% if page >= board.number|add:-2 and page <= board.number|add:2 %}
<span class="{% if page == board.number %}current{% endif %}">
<a href="?pageNum={{ page }}">{{ page}}</a>
</span>
{% elif page >= board.number|add:-3 and page <= board.number|add:3 %}
..
{% endif %}
{% endfor %}
</div><div style="width:35%; margin: 5px; display:inline">
{% if board.has_next %} {# 다음 페이지가 존재 ?#}
<a class="abutton" href="?pageNum={{ board.next_page_number }}">다음</a>
<a class="abutton" href="?pageNum={{ board.paginator.num_pages }}">맨 뒤로</a>
{% endif %}
</div></div></td></tr>
{% endif %}
<tr align="right"><td colspan="5"><a href="../write">[글쓰기]</a></td></tr>
</table>
{% endblock content %}
'수업(국비지원) > Django' 카테고리의 다른 글
| [Django] 게시물 수정, 삭제 (0) | 2023.04.27 |
|---|---|
| [Django] 게시글 상세보기 (0) | 2023.04.27 |
| [Django] 게시판 목록 (0) | 2023.04.27 |
| [Django] 게시판 등록 (0) | 2023.04.27 |
| [Django] 게시판 생성 (0) | 2023.04.27 |