프로그래밍/Django & Flask
[Django Project] 게시글 올리기 & 출력하기
대인보우
2020. 11. 3. 22:52
반응형
과정을 진행하기 전에 유저에게 사진을 입력받고 싶을 땐 media를 등록해야 한다!
게시글 올리기
1. models.py 모델 생성 및 admin 등록
# models.py
class imginfo(models.Model):
id = models.AutoField(primary_key= True) # 자동 id 부여
nickname = models.CharField(max_length=50) # 사용자 닉네임
like_nums = models.IntegerField(max_length=None) # 좋아요 수
photo = models.ImageField(upload_to="img") # 사진
content = models.CharField(max_length=400) # 글 내용
date = models.DateTimeField(auto_now=True) # 글쓴 시각 자동저장
# admin.py
from django.contrib import admin
from post.models import imginfo
# Register your models here.
class imginfoAdmin(admin.ModelAdmin):
list_display = ('id','nickname', 'like_nums', 'photo', 'content', 'date')
admin.site.register(imginfo, imginfoAdmin)
2. post를 입력받을 template 구성 (post_create.html)
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>글쓰기</h1>
<!-- enctype을 꼭 다음과 같이 해주어야 한다. -->
<form class="" action='done/' method="post" enctype="multipart/form-data">
{% csrf_token %}
<!-- 사진과 글만 입력 받을 것이므로 두개만 작성 -->
<input type="file" name="uploadFromPC" value="photo">
<input type="textarea" name="content" value="content">
<input type="submit" value="글쓰기">
</form>
</body>
</html>
3. 게시글이 입력됐다는 것을 확인할 html 작성 (insert_done.html)
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
글 작성이 완료되었습니다.
<a href={% url 'main:index' %}> 홈으로 </a>
</body>
</html>
4. views.py 구성
from django.shortcuts import render
from django.views.decorators.csrf import csrf_protect
from post.models import imginfo
#import os
#from datetime import datetime
#import random
# Create your views here.
def index(request):
return render(request, 'post/post_create.html')
# 게시글 입력
@csrf_protect
def insertform(request):
img = imginfo() # object open
img.photo = request.FILES.get('uploadFromPC') # 이미지 파일 저장
img.nickname = request.session['user_name'] # 유저 닉네임 저장
img.like_nums = 0 # 좋아요 수는 0부터 시작
img.content = request.POST['content'] # 글 내용 저장
img.save() # img에 저장
return render(request, 'post/insert_done.html') # 확인 페이지 return
5. urls.py 구성
from django.contrib import admin
from django.urls import path, re_path
from post import views
app_name = 'post'
urlpatterns = [
re_path(r'^$', views.index, name='index'), # 글쓰기 페이지
re_path(r'^done/$', views.insertform, name='post_insert') # 글 작성하고 완료 페이지
]
여기까지 진행하면 글 작성이 완료된다.
게시글 출력은 다음과 같이 진행한다.
나는 메인화면에 출력할 것이므로 post app이 아닌 main.app에서 작업을 진행했다.
게시글 출력하기
1. main/views.py
from django.shortcuts import render
from post.models import imginfo # post 모델의 imginfo 클래스 import
# Create your views here.
def index(request):
imginfo_list = imginfo.objects.all().order_by('-date')[:10] # 10개까지 게시글 출력
return render(request, 'main/index.html', {'post':imginfo_list})
여기서 주의할 점은 클래스의 이름과 클래스의 값을 저장할 변수의 이름을 같게하면 안된다!! (지역변수 에러 발생)
어쨌든 model을 입력받아 main/index.html로 return 한다. 해당 템플릿을 수정하자
2. main/index.html
<!-- 생략 -->
<section id="main_section">
<!-- 게시글 -->
{% for posting in post %} <!-- post에서 값(1행과 같다)을 하나씩 출력 -->
<div class='diary_box' id="diary">
<div id="first_line">
<div id='like'>
<tr>
<td>좋아요</td>
<td>{{posting.like_nums}}</td>
</tr>
</div>
<div id='edit'>
<tr>
<td>수정</td>
<td>삭제</td>
</tr>
</div>
</div>
<div id="second_line">
<div id='date'>
{{ posting.date }}
</div>
<div id='user_nickname'>
{{ posting.nickname }}
</div>
</div>
<div id="photo">
<!-- 사진을 출력할 땐 다음과 같이 작성하면 된다 -->
<img src="{{ posting.photo.url }}" alt="포토" width="450" height="300">
</div>
<div id='writing'>
{{ posting.content }}
</div>
</div>
{% endfor %}
</section>
반응형