ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • django delete-review by FBV with axios
    Project using python/Cloning Airbnb 2021. 3. 18. 09:51

    url 설정

    config/urls.py

    urlpatterns = [
        path("reviews/", include("reviews.urls", namespace="reviews"))
    ]

    reviews/urls.py

    from django.urls import path
    from reviews import views
    
    app_name = "reviews"
    
    urlpatterns = [
            path("<int:room_pk>/<int:review_pk>/delete/", views.deleteReview, name="delete")
        ]
    

    Client

    review.html

    {% for review in room.reviews.all %}
        <div id="{{review.pk}}">
            <div class="flex justify-between items-center">
                <div class="flex items-center mb-4">
                    {% if review.user.avatar %}
                    <a href="{% url 'users:profile' review.user.pk%}">
                        <img src="{{review.user.avatar.url}}" class="img w-16 h-16 mr-4" alt="User avatar" title="User Avatar">
                    </a>
                    {% else %}
                    <a href="{% url 'users:profile' review.user.pk%}">
                        <div class="img w-16 h-16 mr-4">{{review.user.first_name|first|upper}}</div>
                    </a>
                    {% endif %}
                    <div class="flex flex-col">
                        <span class="font-bold">{{review.user|capfirst}}</span>
                        <span class="text-sm text-gray-400">{{review.created}}</span>
                    </div>
                </div>
                {% if review.user == user %}
                    <div class="w-24">
                        <button class="reviewAmend review_button bg-blue-600 mt-0">Update</button>
                        <button class="reviewDelete review_button bg-red-600 mt-3">Delete</button>
                    </div>
                {% endif %}
            </div>
            <p class="mb-4 font-normal">{{review.review}}</p>
        </div>
    {% endfor %}

    assets/js/deleteReview.js

      django는 form을 post로 server에 submit할 때 무조건 csrf token이 필요하다. .html file에서는 {% csrf_token %}을 추갛면 되지만 JS에서 axios로는 그것이 불가능하다. axios를 이용해서 form을 제출하고 싶다면 다음과 같이 axios.defaults.xsrfCookeName과 axios.defaults.xsrfHeaderName을 추가해줘야 한다.

    import axios from "axios";
    
    axios.defaults.xsrfCookieName = "csrftoken";
    axios.defaults.xsrfHeaderName = "X-CSRFToken";
    
    const reviewDeletes = document.querySelectorAll(".reviewDelete");
    
    const handleDelete = (e) => {
      const btn = e.target;
      const reviewNode = btn.parentNode.parentNode.parentNode;
      const reviewSection = reviewNode.parentNode;
      const review_pk = reviewNode.id;
      const room_pk = window.location.href.split("/")[4];
    
      reviewSection.removeChild(reviewNode);
    
      axios({
        method: "POST",
        url: `/reviews/${room_pk}/${review_pk}/delete/`,
      });
    };
    
    const init = () => {
      if (reviewDeletes) {
        reviewDeletes.forEach((reviewDelete) => {
          reviewDelete.addEventListener("click", handleDelete);
        });
      }
    };
    
    init();
    

    FBV(Function Based View)

    reviews/views.py

    # reviews/views.py
    
    from django.contrib import messages
    from django.http import HttpResponse
    
    from reviews import models as review_models
    
    @login_required
    def deleteReview(request, room_pk, review_pk):
        review = review_models.Review.objects.get_or_none(pk=review_pk)
    
        if review is None:
            messages.error(request, "Review doesn't exist")
    
        if review.user.pk != request.user.pk:
            raise Http404("Page not found")
    
        review.delete()
    
        return HttpResponse(200)
    

    참고 자료

    소스 코드

    github.com/zpskek/airbnb-clone-v3/commit/d49fe8dc996029f1b6f1acbcf9f602e77518e2e7

    'Project using python > Cloning Airbnb' 카테고리의 다른 글

    django show-list by FBV  (0) 2021.04.23
    django toggle-list by FBV  (0) 2021.04.23
    django update-review with axios  (0) 2021.03.18
    django create-review by FBV  (0) 2021.03.18
    django cancel reservation by FBV  (0) 2021.03.17

    댓글

Designed by Tistory.