회원들과 소통을 할 수 있도록 커뮤니티 게시판을 만들었다.
커뮤니티는
작성페이지, 목록페이지, 상세페이지 세 부분이 된다.
먼저, 커뮤니티 클래스를 만들어, 작성자, 날짜, 내용을 입력할 수 있도록 할 것므로
아래와 같이 django안에 models를 만들어주었다.
community models.py
class Community(models.Model) :
author = models.CharField(max_length=60, default='') # 작성자
title = models.CharField(verbose_name='TITLE',max_length=200) # 제목을 가져온다
date = models.DateTimeField('DATE PUBLISHED', default=timezone.now) # 날짜/시간을 가져온다
body = models.TextField('CONTENT', default='') # 본문 내용을 가져온다
mod_date = models.DateTimeField('MODIFY DATE', auto_now=True) # 수정 날짜/시간을 가져온다
class Meta :
verbose_name='community'
verbose_name_plural='communitys'
db_table='community_posts'
ordering = ('-mod_date',)
# 객체 이름을 제목으로 바꿔줌
def __str__(self) :
return self.title
# url 패턴을 만들어준다
def get_absolute_url(self) :
return reverse('community:community_detail', args=(self.id,))
def get_previous(self) :
return self.get_previous_by_mod_date()
def get_next(self) :
return self.get_next_by_mod_date()
작성페이지 html
<form action="" class="p-5 bg-light">
<div class="form-group">
<label for="name">작성자 *</label>
<input type="text" class="form-control" id="name">
</div>
<div class="form-group">
<label for="email">작성 일자 *</label>
<input type="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="website">제목</label>
<input type="url" class="form-control" id="website">
</div>
<div class="form-group">
<label for="body">내용</label>
<textarea name="" id="input-body" cols="30" rows="10" class="form-control"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn py-3 px-4 btn-primary" onclick="alert('글 등록이 완료되었습니다')"><a href="community.html">등록하기</a></button>
</div>
</form>
글쓰기 views.py
# 글쓰기
def write(request) :
if request.method == 'POST':
author = str(request.user) # str type로 바꿔줘야 오류 x
title = request.POST['title']
body = request.POST['body']
post = Community.objects.create(
# Post 객체의 author 필드에 'author' 변수 할당
author=author,
title=title,
body=body,
)
post.writer = author
# save 메서드 호출
post.save()
return HttpResponseRedirect(reverse('community'))
elif request.method == 'GET':
return render(request, 'community_write.html')
글 작성 역시 post메소드일때 실행되도록 한다.
글 작성에 필요한 필드는 작성자, 제목, 본문 이므로 글 작성이 성공이 될 때 post 객체에 작성자, 제목, 본문을 할당한다.
작성자 필드는 문자열이므로 문자열로 변경해줘야한다.
이때 게시글의 작서자는 현재 로그인한 유저이어야하므로 post.writer = author로 해준다.
save메소드는 post객체에 저장한 데이터를 데이터베이스에 저장할 수 있도록 해주는 것이다.
글 작성이 성공이되면 커뮤니티 목록 페이지에 해당 글을 보이게 한다.
상세페이지 html
<span>
<h3 class="mb-3 mt-5">{{details.id}}. {{details.title}}</h3>
</span>
<span>
<p>작성 날짜 : {{details.date}} / 작성자 : {{details.author}}</p>
</span>
<div class="desc">
<p>{{details.body}}</p>
</div>
<form action="{% url 'post_delete' pk=details.pk %}" method="POST">
{% csrf_token %}
<button type="submit" class="btn btn-danger">Delete</button>
</form>
상세페이지 views.py
# 포스팅 세부
def detail(request, pk) :
details = get_object_or_404(Community, pk=pk)
return render(request, 'community_detail.html', {'details' : details})
글 상세 페이지는
번호에 맞는 제목과 내용이 나와야 되는데 번호가 기본키로 저장이 되어있으므로
글 번호를 가져와서 세부 내용을 확인할 수 있도록 한다.
글목록 html
<h3 class="mb-3 mt-5"># 글 목록</h3>
<div class="container">
{%for account in communitys.all%}
<h3><a href="{{account.get_absolute_url}}">{{account.title}}</a></h3>
<p>{{account.mod_date|date:"N d, Y"}}</p>
<!-- <p>{{account.body}}</p> -->
{%endfor%}
</div>
<div id="table1">
<a href="{%url 'detail'%}"><img id="community_table" src="/static/images/community.png" width="700px"></a>
</div>
<br>
<div id="btn">
<p class="mb-0"><a href="{%url 'write' %}" class="btn btn-secondary">글쓰기<span
class="ion-ios-arrow-round-forward"></span></a></p>
</div>
글 작성 시간은 커뮤니티부분에서 시간부분을 입력받았으므로,
mod_date인 장고 데이터를 불러온다.
글목록 views.py
# 커뮤니티
def community(request):
communitys = Community.objects # query set
return render(request, 'community.html', {'communitys' : communitys})
글 목록 페이지는 글 번호와 글 내용이 맞아야하므로
제목을 눌렀을 시 글 번호에 맞는 세부 내용을 보일 수 있도록 id를 작성하여준다.
포스팅 지우기
delete views.py
def post_delete(request, pk):
if request.method == 'POST':
post = Community.objects.get(pk=pk)
if str(post.author) == str(request.user) : # 본인의 게시글일 때
post.delete()
return render(request, 'post_delete.html')
else :
# return HttpResponse('잘못된 접근 입니다.') messages.error(request, "Error")
# return render(request, print("본인의 게시글이 아닙니다."))
# return render(request, 'community_detail.html')
messages.info(request, '본인의 게시글이 아닙니다.')
elif request.method == 'GET':
return HttpResponse('잘못된 접근 입니다.')
글 작성자와 로그인 한 사용자가 일치하면 delete를 할 수 있다.
조건문으로
일치하지 않다면, delete 가 나오지 않는다.