코딩공부/홈페이지 만들기

Django로 홈페이지 만들기 - #6 댓글 쓰기, 댓글 삭제

integerJI 2020. 5. 4. 01:42


참고 사이트

 

보고 배운 곳

https://code1018.tistory.com/248?category=987693

https://code1018.tistory.com/249?category=987693

https://lhy.kr/lecture/django/instagram/02.post-model

 

오늘 사용한 App

myApp

 

사용한 명령어

python manage.py makemigrations

python manage.py migrate

 

포인트

모델의 Post와 Comment의 관계

 - 하나의 게시글엔 여러 개의 댓글이 달릴 수 있다. 1:다의 관계

 

완성된 git ( 2020.06.18 키 노출로 인한 git 비공개 )

https://github.com/integerJI/int_1

 

aws key 노출되다.

https://integer-ji.tistory.com/200

 

aws key 생성시 주의 할점

https://integer-ji.tistory.com/208


사용한 디렉터리 계층구조 및 파일


myApp

 

# myProject/myApp/admin.py

from django.contrib import admin
from .models import Post, Comment

# Register your models here.
admin.site.register(Post)
admin.site.register(Comment)
# myProject/myApp/models.py

class Comment(models.Model):
    comment = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, related_name='comments')
    comment_text = models.CharField(max_length=200)
    comment_user = models.ForeignKey(User, on_delete=models.CASCADE, null = True)
    comment_date = models.DateTimeField('date published', default=timezone.now)
    comment_update_date = models.DateTimeField('date published', null = True, default=timezone.now)
    
    class Meta:
        ordering = ['-id']
            
    def __str__(self):
        return '%s - %s' % (self.comment_user, self.comment_text) 
# myProject/myApp/urls.py

path('c_post/<int:post_id>', views.c_post, name="c_post"),
path('c_post/<int:post_id>/<int:comment_id>', views.c_delete, name="c_delete"),
# myProject/myApp/views.py

from .models import Post, Comment

@login_required
def c_post(request, post_id):
    if request.method =='POST':
        comment = get_object_or_404(Post, id=post_id)
        comment_text = request.POST.get('comment_text')
        comment_user = User.objects.get(username = request.user.get_username())
        Comment.objects.create(comment=comment, comment_text=comment_text, comment_user=comment_user)

        if request.POST.get('app_url') == '/myApp/index/':
            return redirect(reverse('index'), post_id)
        else :
            return redirect('detail', post_id)

@login_required
def c_delete(request, post_id, comment_id):
    post = get_object_or_404(Post, id=post_id)
    comment = get_object_or_404(Comment, id=comment_id)

    conn_profile = User.objects.get(username = request.user.get_username())

    if request.method =='POST':
        if conn_profile == post.create_user:
            comment.delete()
            if request.POST.get('app_url') == '/myApp/index/':
                return redirect(reverse('index'), post_id)
            else :
                return redirect('detail', post_id)
        else:
            messages.info(request, '삭제할 수 없습니다.')
            return render(request, 'detail.html', {'post': post})
<!-- myProject/myApp/templates/index.html -->

# .. 생략

{% for post in posts.all %}
<div class="card-deck mb-3">
    <div class="card mb-4 shadow-sm">
        <div class="card-header">
            <div class="btn-group" style="float: left;">
                <a class="my-0 font-weight-normal" href="#"><span class="writer_name">{{ post.create_user }}</span></a>
            </div>
            <div class="btn-group" style="float: right;">
                <span class="hidden" id="control_id">
                    <a href="{% url 'update' post.id %}"><img src="/static/update.png" alt="update"
                            style="width: 1.5rem; height:1.5rem;">&nbsp;</a>
                    <a href="{% url 'delete' post.id %}" onclick="return confirm('정말 삭제하시겠습니까?')"><img
                            src="/static/delete.png" alt="delete" style="width: 1.5rem; height:1.5rem;"></a>
                </span>
            </div>
        </div>
        {% if post.create_img %}
        <div class="text-center">
            <img src="{{post.create_img.url}}" class="rounded" alt="..." width="585.5dp" height="585.5dp">
        </div>
        {% else %}
        <a>no</a>
        {% endif %}
        <div class="card-body">

            <a href="{% url 'detail' post.id %}"><img src="/static/detail.png" alt="detail 이동"
                    style="width: 2rem; height:2rem;"></a>
            <div class="group">

                # .. new

                <small class="text-muted">{{post.comments.count}} comment</small>
                <br>
                <a class="my-0 font-weight-normal" href="#">{{ post.create_user }}</a>
                <a class="card-title pricing-card-title">{{ post|safe|linebreaksbr }}</a>
                <br>

                {% for comment in post.comments.all %}
                <a class="card-text" href="#"><span class="comment_writer_name">{{comment.comment_user}}</span></a>
                <a class="card-text">{{comment.comment_text}}
                    <span class="control hidden" id="control_id1{{ forloop.counter0 }}">
                        <form action="{% url 'c_delete' post.pk comment.pk %}" method="POST"
                            style="display:inline-block">
                            {% csrf_token %}
                            <input type="`" name="app_url" id="app_url" value="{{app_url}}" />
                            <button type="submit">삭제</button>
                        </form>
                    </span>
                    <br>
                    {% endfor %}
                    <small class="text-muted">{{ post.create_date }}</small>
                    <br>
                    <div class="group">
                        <form action="{% url 'c_post' post.id %}" method="POST">
                            {% csrf_token %}
                            <div class="input-group input-group-sm mb-3">
                                <input type="text" class="form-control" aria-label="Sizing example input"
                                    aria-describedby="inputGroup-sizing-sm" name="comment_text" id="comment_text"
                                    placeholder="댓글 달기 ..." style="display:inline-block">
                                <input type="hidden" name="app_url" id="app_url" value="{{app_url}}" />
                                <div class="input-group-prepend">
                                    <button class="input-group-text" id="inputGroup-sizing-sm" type="submit">게시</button>
                                </div>
                            </div>
                        </form>
                    </div>

            </div>
        </div>
    </div>
</div>
{% endfor %}

# .. 생략
# .. 생략

<div class="card-body">

    <a href="{% url 'detail' post.id %}"><img src="/static/detail.png" alt="detail 이동"
            style="width: 2rem; height:2rem;"></a>
    <br>
    <small class="text-muted">{{post.comments.count}} comment</small>
    <hr>
    <a class="card-title pricing-card-title">{{ post|safe|linebreaksbr }}<small
            class="text-muted">&nbsp;&nbsp;{{ post.create_date }}</small></a>
    <hr>

    # .. new

    {% for comment in post.comments.all %}
    <a class="card-text" href="#"><span class="comment_writer_name">{{comment.comment_user}}</span></a>
    <small class="text-muted">{{comment.comment_date}}</small>
    <br>
    <a class="card-text">{{comment.comment_text}}
        <span class="control hidden" id="control_id1{{ forloop.counter0 }}">
            <form action="{% url 'c_delete' post.pk comment.pk %}" method="POST" style="display:inline-block">
                {% csrf_token %}
                <input type="hidden" name="app_url" id="app_url" value="{{app_url}}" />
                <button type="submit">삭제</button>
            </form>
        </span>
        <br>
        {% endfor %}
        <form action="{% url 'c_post' post.id %}" method="POST">
            {% csrf_token %}
            <div class="input-group input-group-sm mb-3">
                <input type="text" class="form-control" aria-label="Sizing example input"
                    aria-describedby="inputGroup-sizing-sm" name="comment_text" id="comment_text"
                    placeholder="댓글 달기 ..." style="display:inline-block">
                <input type="hidden" name="app_url" id="app_url" value="{{app_url}}" />
                <div class="input-group-prepend">
                    <button class="input-group-text" id="inputGroup-sizing-sm" type="submit">게시</button>
                </div>
            </div>
        </form>
</div>
</aside>

# ... 생략

마무리