Django/inflearn

R : 게시글 상세 화면 구현하기

곽수진 2022. 11. 11. 01:56
반응형

from django.shortcuts import render, get_object_or_404
from third.models import Restaurant
from django.core.paginator import Paginator
from third.forms import RestaurantForm
from django.http import HttpResponseRedirect

# Create your views here.
def list(request):
    restaurants = Restaurant.objects.all()
    paginator = Paginator(restaurants, 5)

    page = request.GET.get('page')
    items = paginator.get_page(page)

    context = {
        'restaurants': items
    }
    return render(request, 'third/list.html', context)


def create(request):
    if request.method == 'POST':
        form = RestaurantForm(request.POST)
        if form.is_valid():
            new_item = form.save()
        return HttpResponseRedirect('/third/list/')
    form = RestaurantForm()
    return render(request, 'third/create.html', {'form': form})


def update(request):
    if request.method == 'POST' and 'id' in request.POST:
        # item = Restaurant.objects.get(pk=request.POST.get('id'))
        item = get_object_or_404(Restaurant, pk=request.POST.get('id'))
        form = RestaurantForm(request.POST, instance=item)
        if form.is_valid():
            item = form.save()
    elif request.method == 'GET':
        # item = Restaurant.objects.get(pk=request.GET.get('id'))
        item = get_object_or_404(Restaurant, pk=request.GET.get('id'))
        form = RestaurantForm(instance=item)
        return render(request, 'third/update.html', {'form': form})
    return HttpResponseRedirect('/third/list/')


def detail(request):
    if 'id' in request.GET:
        item = get_object_or_404(Restaurant, pk=request.GET.get('id'))
        return render(request, 'third/detail.html', {'item': item})
    return HttpResponseRedirect('/third/list/')

▶ views.py 파일에 detail 메소드 추가

if 'id' in request.GET : GET으로 받은 id값 존재 여부 확인

item  = get_object_or_404('restaurant, pk=request.GET.get('id')) : GET으로 받은 id값이 존재하지 않을 경우 404 에러 발생

 

 

{% extends 'third/base.html' %}
{% load static %}
{% block content %}
<div class="container">
  <div class="row">
    <div class="col-sm-12" style="margin-top:20px;">
      <h3>{{ item.name }}</h3>
      <p>
        {{ item.address }}
      </p>
    </div>
  </div>
</div>
{% endblock %}

▶ third 폴더에 detail.html 파일 생성

    → 간단하게 item 인스턴스에 들어 있는 name 필드 값과 address 필드 값이 출력되도록 작성

 

 

from django.urls import path
from . import views

urlpatterns = [
    path('list/', views.list, name="list"),
    path('create/', views.create, name="restaurant-create"),
    path('update/', views.update, name="restaurant-update"),
    path('detail/', views.detail, name="restaurant-detail")
]

▶ urls.py 파일에 새로운 경로 추가

 

 

{% extends 'third/base.html' %}
{% load static %}
{% block content %}
<div class="container">
    {% for item in restaurants %}
    <div class="row restaurant-item" style="margin:20px auto;">
        <div class="col-sm-12">
            <div class="card border-secondary">
                <div class="card-body">
                    <h5 class="card-title">{{ item.name }}</h5>
                    <h6 class="card-subtitle mb-2 text-muted">{{ item.address }}</h6>
                    <p class="card-text">음식점 설명</p>
                    <a href="{% url 'restaurant-detail' %}?id={{ item.id }}" class="card-link">자세히 보기</a>
                    <a href="{% url 'restaurant-update' %}?id={{ item.id }}" class="card-link">수정하기</a>
                </div>
            </div>
        </div>
    </div>
    {% endfor %}

    <div class="row">
        <div class="col-sm-12 text-center">
            <div class="pagination">
                <span class="step-links text-center" style="width:100%;">
                    {% if restaurants.has_previous %}
                        <a href="?page=1">&laquo;</a>
                        <a href="?page={{ restaurants.previous_page_number }}">{{ restaurants.previous_page_number }}</a>
                    {% endif %}
                    <span class="current">
                        {{ restaurants.number }}
                    </span>
                    {% if restaurants.has_next and restaurants.next_page_number != restaurants.paginator.num_pages %}
                        <a href="?page={{ restaurants.next_page_number }}">{{ restaurants.next_page_number }}</a>
                        <a href="?page={{ restaurants.paginator.num_pages }}">{{ restaurants.paginator.num_pages }}</a>
                    {% elif restaurants.has_next and restaurants.next_page_number == restaurants.paginator.num_pages %}
                        <a href="?page={{ restaurants.next_page_number }}">{{ restaurants.next_page_number }}</a>
                    {% endif %}
                </span>
            </div>
        </div>
    </div>
</div>
{% endblock %}

▶ 기존 음식점 리스트 화면에서 자세히보기 링크를 클릭했을 경우 상세 페이지로 넘어가도록 수정

반응형

'Django > inflearn' 카테고리의 다른 글

Relation 개요  (2) 2022.11.30
D : 게시글 삭제 구현하기  (0) 2022.11.12
U : 게시글 수정 구현하기  (0) 2022.11.10
C : 게시글 등록 구현하기  (0) 2022.11.09
R : 페이지 구현하기  (0) 2022.11.08