django를 활용하여 댓글 권한을 설정해 보자
코드는 아래 링크 내용에서 이어진다.
https://edder773.tistory.com/170
사용자가 작성한 댓글의 권한을 설정해 보자
모델의 관계를 설정해 주기 위해서 articles의 models.py의 Comment 클래스에 다음과 같이 user를 추가해주자.
class Comment(models.Model):
article = models.ForeignKey(Article, on_delete = models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
content = models.CharField(max_length=100)
def __str__(self):
return self.content
models.py를 수정했으니, 저장 후 필수적으로 migrate를 진행해 주자
makemigrate를 진행할 경우 아래와 같은 경고문이 뜬다.
기본적으로 모든 칼럼은 NOT NULL 제약 조건이 있어서 데이터 없이 새로 추가되는 외래 키 필드 user_id가 생성되지 않으므로 기본값을 어떻게 할지 선택해야 한다.
1을 입력 후 진행해 주자
article의 user_id에도 어떤 데이터를 넣을지 입력하라는 경고가 뜬다. 1을 입력하고 진행하자.
그러고 나서 다시 migrate를 진행해 주자.
여기까지 user를 만들었다면 이제 인증된 회원만 댓글을 수정하고 지우고 할 수 있도록 권한을 만들어보자.
먼퍼 views.py의 comment_create를 작성자 정보가 저장될 수 있도록 수정해보자.
def comment_create(request,pk):
article = Article.objects.get(pk=pk)
commentform = CommentForm(request.POST)
if commentform.is_valid():
comment = commentform.save(commit=False)
comment.article = article
comment.user = request.user
comment.save()
return redirect('articles:read', article.pk)
이제 작성한 댓글의 작성자를 출력할 수 있게 read.html을 수정해주자.
<ul>
{% for comments in comment %}
<li> {{comments.user}} - {{comments.content}}
<form action="{% url 'articles:comment_delete' article.pk comments.pk %}" method = "POST">
{% csrf_token %}
<input type="submit" value="삭제">
</form>
</li>
{%empty%}
<p>댓글이 없습니다.</p>
{% endfor %}
</ul>
또한 댓글도 작성자만 삭제 할 수 있도록, 코드를 수정해주자.
def comment_delete(request, article_pk, comment_pk):
comment = Comment.objects.get(pk=comment_pk)
if request.user == comment.user:
comment.delete()
return redirect('articles:read', article_pk)
또, 댓글의 작성자가 아니라면 삭제 버튼이 출력되지 않게 수정하자.
{% if request.user == comments.user %}
<form action="{% url 'articles:comment_delete' article.pk comments.pk %}" method = "POST">
{% csrf_token %}
<input type="submit" value="삭제">
</form>
{% endif %}
마지막으로 인증된 사용자만 댓글을 작성 할 수 있도록 작성해보자
def comment_create(request,pk):
if request.user.is_authenticated:
article = Article.objects.get(pk=pk)
commentform = CommentForm(request.POST)
if commentform.is_valid():
comment = commentform.save(commit=False)
comment.article = article
comment.user = request.user
comment.save()
return redirect('articles:read', article.pk)
else :
return redirect('accounts:login')
마찬가지로 인증된 사용자인 경우만 댓글을 삭제할 수 있게 설정해주자.
def comment_delete(request, article_pk, comment_pk):
if request.user.is_authenticated:
comment = Comment.objects.get(pk=comment_pk)
if request.user == comment.user:
comment.delete()
return redirect('articles:read', article_pk)
else :
return redirect('accounts:login')
인증되지 않은 사용자는 댓글 form을 볼 수 없게 만들어주자.
{% if request.user.is_authenticated %}
<form action="{% url 'articles:comment_create' article.pk %}" method = "POST">
{% csrf_token %}
{{ commentform }}
<input type="submit" value="댓글등록">
</form>
{% else %}
댓글을 작성하려면 <a href="{% url 'accounts:login' %}">로그인</a>하세요
{% endif %}
이제 서버를 작동하여 정상 작동하는지 확인해보자.
비 로그인시 화면
로그인시 화면
내가 작성한 댓글 삭제 여부
정상적으로 서버가 동작함을 확인 할 수 있다.
'개발 > Django' 카테고리의 다른 글
[Django] REST framework를 이용한 Rest API 사용해보기 (0) | 2023.04.24 |
---|---|
[Django] OPEN API를 이용하여 값 출력해보기 (0) | 2023.04.24 |
[Django] 게시판 권한 설정해보기 (0) | 2023.04.12 |
[Django] 게시판 댓글 기능 구현 해보기 - Part 3 (0) | 2023.04.12 |
[Django] 게시판 댓글 기능 구현 해보기 - Part 2 (0) | 2023.04.10 |
댓글