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

Django로 홈페이지 만들기 - #5 글 수정, 글 삭제

integerJI 2020. 5. 4. 01:16


참고 사이트

 

글 수정 기능 만들기

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

 

글 삭제 기능 만들기

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

 

form을 이용한 글 수정 페이지 수정

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

 

오늘 사용한 App

myApp

 

생성한 파일 & 폴더

myApp/tamplates/update.html - 파일 생성

 

포인트

static로 넣어준 img 파일을 사용한다

수정과 삭제 view함수의 로직 중요

본격 javascript 사용

 

완성된 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/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">
      <a class="my-0 font-weight-normal" href="#">{{ post.create_user }}</a>
      <a class="card-title pricing-card-title">{{ post|safe|linebreaksbr }}</a>
      <br>
        <small class="text-muted">{{ post.create_date }}</small>
      </div>
    </div>
  </div>
</div>
{% endfor %}

# ... 생략
<!-- myProject/myApp/templates/detail.html -->

# ... 생략

<aside class="col-md-3 blog-sidebar">
    <div class="card-header">
        <div class="d-flex justify-content-between align-items-center">
            <div class="btn-group">
                <a class="my-0 font-weight-normal" href="#"><span
                        class="writer_name">{{ post.create_user }}</span></a>
            </div>
            <div class="btn-group">
                <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>
    </div>
    <div class="card-body">

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

# ... 생략
<!--myProject/myApp/templates/update.html-->

{% extends 'base.html' %}
{% block content %}

<body>
    <form method="POST" action="" enctype="multipart/form-data" id="form1" runat="server">
        {%csrf_token%}
        <main role="main" class="container">
            <div class="row justify-content-center">
                <div class="col-md-7 blog-main">
                    <div class="container">
                        <div class="form-group">
                            <img id="blah" src="{{post.create_img.url}}" alt="your image" width="585.5dp"
                                height="585.5dp" />
                        </div>
                    </div>
                </div>
                <aside class="col-md-3 blog-sidebar">
                    <div class="form-group">
                        {{form.create_img}}
                        {{form.main_text}}
                    </div>
                    <div style="float: right;">
                        <input class="btn btn-dark" type="submit" value="post">
                    </div>
                </aside>
            </div>
        </main>
    </form>
</body>
{% endblock %}
# myProject/myApp/views.py

def update(request, post_id):
    post = Post.objects.get(id = post_id)
    conn_profile = User.objects.get(username = request.user.get_username())
        
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES, instance=post)

        if form.is_valid():
            if conn_profile == post.create_user:
                post = form.save(commit=False)
                post.save()

                context = {'post': post, 'form': form}
                content = request.POST.get('content')
                        
                messages.info(request, '수정 완료')
                return render(request, 'detail.html', context=context)
                
            else:
                messages.info(request, '수정할 수 없습니다.')
                return render(request, 'detail.html', {'post': post})
    else:
        if conn_profile == post.create_user:
            form = PostForm(instance = post)
            return render(request, 'update.html', {'post': post, 'form': form})
        else:
            messages.info(request, '수정할 수 없습니다.')
            return redirect(reverse('index'), post_id)
            
def delete(request, post_id):
    post = get_object_or_404(Post, id=post_id)

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

    if conn_profile == post.create_user:
        post.delete()
        return redirect(reverse('index'))
    else:
        messages.info(request, '삭제할 수 없습니다.')
        return render(request, 'detail.html', {'post': post})
# myProject/myApp/urls.py

path('update/<int:post_id>', views.update, name="update"),
path('delete/<int:post_id>', views.delete, name="delete"),

마무리