3

我们如何使用通用视图django-mptt实现 CRUD 功能?我进行了很多搜索,但找不到单个教程/示例代码。

假设我们有一个课程层次结构或类别层次结构,或类似的东西......我们如何添加/删除/更新/读取它们?

例如我有这个模型:

from django.db import models
from mptt.models import MPTTModel , TreeForeignKey


class Genre(MPTTModel):
    name            = models.CharField(max_length = 50 , unique = True)
    parent          = TreeForeignKey('self' , null = True , blank = True , related_name = 'children')

    class MPTTMeta:
        order_insertion_by = ['name']

这个views.py:

from django.views.generic.list_detail import object_list
from mp.models import Genre

def genres_list(request):
    ''' Shows all of the genres '''
    return object_list(request,
            queryset = Genre.tree.all() ,
            template_name = 'genres.html' ,
            # template_object_name = 'nodes' ## Adding "nodes" variable didn't solve the problem
    )

好吧...我收到此错误(错误在行号“5”中:{% recursetree nodes %}):

Caught VariableDoesNotExist while rendering: Failed lookup for key [nodes] in u"[{'paginator': None, 'is_paginated': False, 'page_obj': None, 'nodes_list': [<Genre: Genre object>, <Genre: Genre object>, <Genre: Genre object>, <Genre: Genre object>]}, {'csrf_token': <django.utils.functional.__proxy__ object at 0x7f5bb810f090>}, {'perms': <django.utils.functional.__proxy__ object at 0x7f5bb810ff10>, 'messages': <django.contrib.messages.storage.user_messages.LegacyFallbackStorage object at 0x324af50>, 'user': ....................................

    <html>
2   
3       {% load mptt_tags %}
4       <ul>
5           {% recursetree nodes %}
6           <li>
7               {{node.name}}
4

1 回答 1

8

具有 MPTT 模型和基于类的通用视图的简单 CRUD 应用程序(Django 1.4基于函数的实现已被弃用)。

让我们开始

网址.py

from django.conf.urls.defaults import patterns, include, url
from django.views.generic import DetailView, ListView, CreateView, UpdateView
from genre.models import Genre

urlpatterns = patterns('',
    url(r'detail/(?P<pk>\d+)', DetailView.as_view(model=Genre), name="genre_detail",),
    url(r'update/(?P<pk>\d+)', UpdateView.as_view(model=Genre), name="genre_update",),
    url(r'create', CreateView.as_view(model=Genre), name="genre_create",),
    url(r'list', ListView.as_view(model=Genre), name="genre_list",),
)

模型.py

from django.core.urlresolvers import reverse
from django.db import models
from mptt.models import MPTTModel


class Genre(MPTTModel):
    name = models.CharField(max_length=50 , unique=True)
    parent = models.ForeignKey('self' , null=True , blank=True , related_name='children')

    def get_absolute_url(self):
        return reverse('genre_detail', kwargs={'pk': self.pk, })

    class MPTTMeta:
        order_insertion_by = ['name']

模板/流派_detail.html

<html>
<body>

<div>Object: {{ object }}</div>
<div>Object's name: {{ object.name }}</div>
<div>Object's parent: {{ object.parent }}</div>

</body>
</html>

模板/流派_form.html

<html>
<body>

<form action="" method="post">
{% csrf_token %}
{{ form.as_ul }}

<button>save</button>
</form>
</body>
</html>

模板/流派列表.html

{% load mptt_tags %}
<html>
<body>
<ul class="root">
    {% recursetree object_list %}
        <li>
            {{ node.name }}
            {% if not node.is_leaf_node %}
                <ul class="children">
                    {{ children }}
                </ul>
            {% endif %}
        </li>
    {% endrecursetree %}
</ul>
</body>
</html>

就是这样。

我今天有一些空闲时间,并在 github https://github.com/kaygorodov/simple-crud-mptt上分享了这个项目。

如何定义自己的基于类的视图?

流派/views.py

from django.view.generic import UpdateView
class MyCustomUpdateView(UpdateView):
    model = Genre

    def get_form_kwargs(self):
        """
        Returns the keyword arguments for instanciating the form.
        """
        kwargs = super(MyCustomUpdateView, self).get_form_kwargs()
        kwargs.update({'my_first_param_to_init_form': 1,
                      'my_second_param_to_init_form': 2,
        })
        return kwargs

流派/urls.py

url(r'update/(?P<pk>\d+)', MyCustomUpdateView.as_view(), name="genre_update",),
于 2012-07-17T04:56:30.627 回答