8👍
✅
Simple CRUD application with MPTT models and class-based generic views (Django 1.4 The function-based implementation has been deprecated).
Let’s begin
urls.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",),
)
models.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']
templates/genre_detail.html
<html>
<body>
<div>Object: {{ object }}</div>
<div>Object's name: {{ object.name }}</div>
<div>Object's parent: {{ object.parent }}</div>
</body>
</html>
templates/genre_form.html
<html>
<body>
<form action="" method="post">
{% csrf_token %}
{{ form.as_ul }}
<button>save</button>
</form>
</body>
</html>
templates/genre_list.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>
and that’s it.
I had some spare time today and shared this project on github https://github.com/kaygorodov/simple-crud-mptt.
How can I define my own class-based view?
genre/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
genre/urls.py
url(r'update/(?P<pk>\d+)', MyCustomUpdateView.as_view(), name="genre_update",),
Source:stackexchange.com