django-mptt 사용자 view

이전글 django-mptt로 tree 구조 만들기.에 이어 사용자에게 보여주는 페이지에서 tree구조를 보여주려면, view.py에 view 함수와 template을 만들어주어야한다.

먼저, view.py에 아래와 같이 view함수를 만들어준다.

아래처럼, Category 모델을 모두 불러와서 템플릿에 데이타를 보내는 뷰를 작성한다.

from django.shortcuts import render

# Create your views here.
from django.views.generic import View
from .models import Category

class CategoryView(View):
    template_name = 'tracer/category.html'
    def get(self, request):
        context = {'categories': Category.objects.all()}

        return render(request, self.template_name, context)

이제, 사용자에게 보여줄 템플릿을 작성하면된다.

{% load mptt_tags %}

{% block content %}
<style>
    .menu a {cursor:pointer;}
    .menu .hide{display:none;}
</style>
    <ul class="root">
        {% recursetree categories %}
        <li class="menu">
            <a>{{ node.name }}</a>
            {% if not node.is_leaf_node %}
            <ul class="hide">
                {{ children }}
            </ul>
        {% endif %}
        </li>
        {% endrecursetree %}
    </ul>

<script src="//code.jquery.com/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        $(".menu>a").click(function(){
            $(this).next("ul").toggleClass("hide");
        });
    });
</script>

{% endblock content %}

2 comments

    • 치킨놈 on 2020년 7월 15일 at 4:47 오후
    • Reply

    안녕하세요.
    웹 개발에 관심있는 학생인데요.

    템플릿을 어떻게 구성해야하는지 더 자세히 알고 싶습니다.
    urls.py의 urlpatterns에 링크되는 path,
    category.html에서 {% load mptt_tags %}는 어떻게 사용 되는지, {% recursetree categories %}도요..

    시간되실때 답변 부탁드립니다.
    감사합니다.

      • snowffox on 2020년 7월 17일 at 2:20 오후
      • Reply

      질문하신 내용은, django를 공부하고 사용해 보는 방법 밖에 없다고 생각됩니다.
      템플릿에 사용한 load mptt-tags 는 custom template tag로 django-mptt를 개발하신 분들이 만든 사용자 정의 태그여서, django 표준 템플릿 태그는 아닙니다. 그러니까, django-mptt 를 설치하고 사용하려면 저렇게 하는구나 하고 넘어가고, 더욱 세세한 내용을 알고 싶으면, 문서를 참고해서 알아보는 방법밖엔 없습니다.
      저도 초보라서, 더 자세히 설명하기가 쉽지 않네요. ;^^

      custom template tag는, https://docs.djangoproject.com/en/3.0/howto/custom-template-tags/
      django-mptt는 https://django-mptt.readthedocs.io/en/latest/
      문서를 참고하시면 됩니다.

답글 남기기

Your email address will not be published.