-
django edit-photo by CBVProject using python/Cloning Airbnb 2021. 3. 12. 11:34
url 설정
config/urls.py
urlpatterns = [ path("rooms/", include("rooms.urls", namespace="room")) ]
rooms/urls.py
from django.urls import path from . import views app_name = "rooms" urlpatterns = [ path( "<int:room_pk>/photos/<int:photo_pk>/edit/", views.EditPhotoView.as_view(), name="edit-photo", )]
CBV(Class Based View)
rooms/views.py
CBV는 django에서 정의한 여러가지 View들을 이용한다. 그 중 UpdateView를 이용해서 edit-photo page를 작성한다.
# rooms/views.py from django.views.generic import CreateView from django.http import Http404 from django.shortcuts import redirect, reverse from users import mixins from photos import models as photo_models from rooms import forms class EditPhotoView( mixins.LoggedInOnlyView, mixins.HostOnlyView, SuccessMessageMixin, UpdateView ): """ Edit Photo View Definition """ model = photo_models.Photo template_name = "pages/rooms/photos/edit_photo.html" fields = ("caption",) pk_url_kwarg = "photo_pk" success_message = "Photo Updated" def get_form(self, form_class=None): form = super().get_form(form_class=form_class) form.fields["caption"].widget.attrs = {"placeholder": "Caption"} return form def get_object(self, queryset=None): photo = super().get_object(queryset=queryset) if self.request.user.pk != photo.room.host.pk: raise Http404("Page not found") return photo def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) photo = context["photo"] context["room"] = photo.room return context def get_success_url(self): room_pk = self.kwargs.get("room_pk") return reverse("rooms:photo-list", kwargs={"pk": room_pk})
templates
pages/rooms/photos/edit_photo.html
{% extends 'base.html' %} {% block page_title %} Edit {{room.name}}'s Photo {% endblock page_title %} {% block search-bar %} <div></div> {% endblock search-bar %} {% block content %} <div class="background"> <div class="wrap"> <h1 class="text-3xl font-bold pb-6 pt-3 text-center">Edit Photo('{{photo}}')</h1> <form method="post" class="form" enctype="multipart/form-data"> {% csrf_token %} <div class="form_input rounded-lg flex"> <label for="caption">Caption:</label> {{form.caption}} </div> <button class="form_button">Edit</button> </form> <button class="button bg-gray-700"> <a href="{% url 'rooms:photo-list' room.pk %}">Back</a> </button> </div> </div> {% endblock content %}
참고 자료
- 노마드 코더의 Airbnb 클론 강의
소스 코드
github.com/zpskek/airbnb-clone-v3/commit/8c6316a04b0a9f448336c8726e65a31220a49340
'Project using python > Cloning Airbnb' 카테고리의 다른 글
django 'reserve a room' by FBV (0) 2021.03.13 django delete-photo by FBV (0) 2021.03.12 django edit photo by FBV (0) 2021.03.12 django create-photo by CBV (0) 2021.03.12 django create-photo by FBV (0) 2021.03.12