Advertisement
johnmahugu

Django - full crud app tutorial

Jul 23rd, 2015
566
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 17.58 KB | None | 0 0
  1. May 19th, 2013
  2. Simple CRUD App in Django
  3. Tutorial for: Django
  4.  
  5. This tutorial will explain how to create a super quick data-driven application using Django 1.5.
  6.  
  7. I build lots of custom web applications, I use Django because it makes modeling the data I will use super simple. This tutorial assumes you already have a Django project ready to go by using django-admin.py startproject and it's all configured how you like it. I would also recommend using South, this tutorial will not go into how to use it, just read the simple tutorial provided by the project's documentation.
  8.  
  9. So first, you will need to create an app in your Django project and create a few extra files there to make it more stand-alone and plug-able into different projects. Go into the app's directory and create the following files: forms.py, and urls.py. Next create a directory called templates and inside there create a directory with the same name as your app. For this example, we will be creating a Django app which will allow us to manage a simple Name and Phone number address book, nothing too special. It will have a single relation to a Category model which will allow you to easily sort through Family, Friends and Co-workers. We will also add some other fields for the purpose of displaying what types of interesting fields you can make available. So, we'll be calling this app people for the rest of this tutorial.
  10.  
  11. First lets get the basic modeling done, which will be the database tables:
  12.  
  13. from django.db import models
  14. from django.template.defaultfilters import slugify
  15. from django.contrib.localflavor.us.models import PhoneNumberField
  16.  
  17. class Category(models.Model):
  18.     title = models.CharField(max_length=80)
  19.     slug = models.SlugField(blank=True)
  20.     class Meta:
  21.         verbose_name_plural = 'categories'
  22.     def __unicode__(self):
  23.         return u"%s" % self.title
  24.     def save(self, *args, **kwargs):
  25.         self.slug = slugify(self.title)
  26.         return super(Category, self).save(*args, **kwargs)
  27.     @models.permalink
  28.     def get_absolute_url(self):
  29.         return ('category_detail', [self.slug])
  30.     @models.permalink
  31.     def get_update_url(self):
  32.         return ('category_update', [self.slug])
  33.     @models.permalink
  34.     def get_delete_url(self):
  35.         return ('category_delete', [self.slug])
  36.  
  37. class Person(models.Model):
  38.     PROXIMITY_LIST = (
  39.         (0, 'Not sure'),
  40.         ('Friends', (
  41.             (10, 'Best friends forever'),
  42.             (20, 'Close friends'),
  43.             (30, 'Distant friends'),
  44.             (40, 'Enemies til the end')
  45.         )),
  46.         ('Family', (
  47.             (50, 'Super close'),
  48.             (60, 'Only on occasion'),
  49.             (70, 'Only at funerals'),
  50.             (80, 'Family grouch!')
  51.         )),
  52.     )
  53.     first_name = models.CharField(max_length=60, help_text='Their first name')
  54.     last_name = models.CharField(max_length=80, blank=True, help_text='Do you know it?')
  55.     slug = models.SlugField(blank=True)
  56.     category = models.ForeignKey(Category, blank=True, null=True, help_text='File this person where?')
  57.     proximity = models.PositiveSmallIntegerField(choices=PROXIMITY_LIST, help_text='How much of a distance to keep?')
  58.     home_phone = PhoneNumberField(blank=True)
  59.     cell_phone = PhoneNumberField(blank=True)
  60.     email = models.EmailField(blank=True, help_text='Do they have an Email address?')
  61.     added_on = models.DateField(auto_now_add=True)
  62.     class Meta:
  63.         verbose_name_plural = 'people'
  64.         ordering = ['last_name']
  65.     @property
  66.     def full_name(self):
  67.         return u"%s %s" % (self.first_name, self.last_name) if self.last_name != '' else u"%s" % self.first_name
  68.     def __unicode__(self):
  69.         return u"%s, %s" % (self.last_name, self.first_name) if self.last_name != '' else u"%s" % self.first_name
  70.     def save(self, *args, **kwargs):
  71.         self.slug = slugify(self.full_name)
  72.         return super(Person, self).save(*args, **kwargs)
  73.     @models.permalink
  74.     def get_absolute_url(self):
  75.         return ('person_detail', [self.slug])
  76.     @models.permalink
  77.     def get_update_url(self):
  78.         return ('person_update', [self.slug])
  79.     @models.permalink
  80.     def get_delete_url(self):
  81.         return ('person_delete', [self.slug])
  82.  
  83. Okay, let me explain what some of this does. Let's begin with the Category model, it tells us that we want a title and a slug for it. A slug is used the URL of the application to make it easier to know what your visiting when sharing links with people. Although we don't need to use it for this example, I thought I'd explain how to use slugs for future applications you may create. You may notice that we have a Meta class here, verbose_name_plural is specifically used for the Django admin, if you choose to use it with this app. ordering is used globally to easily define how the data should be ordered. Since this app is focusing on a CRUD example, I'd like to avoid using the admin interface. The __unicode__ method provides a human readable format of the object. If your familiar with Django at all, you may have noticed that I overwrote the save() method, this is to handle the auto slugification of the title, it is entirely optional in Django to define a save() method, as one already exists that does all the dirty work, and this is why we also call it after slugifying the title. The final part of the class is the get_absolute_url() method, which is going to be used to make a few of the CRUD components work, and we will also call it in our templates. It provides a way to keep all URLs DRY and pointing to the correct location at all times. Something not common, but included to display how to be more DRY, is adding methods to assist in various CRUD operations, such as updating and deleting. Those last two methods in each model are used in the templates which we will get to later on in this tutorial. You'll see how much simpler and readable your template code will look when using this method. Again, it is completely optional, you can always use the url template tag for this instead. However, this will be more difficult if you choose to create generic templates as we will do in this tutorial. This tutorial is focusing on being as DRY as possible and reusing as much code as possible.
  84.  
  85. The Person has some very similar components, so I won't explain them a second time. The first thing we see here is a PROXIMITY_LIST variable. This is used for a choice field in this model. Feel free to add or remove any of them, it is more or less there for humor. Other fields used are the ForeignKey into the Category model. The proximity field shows how to use the list created in a choice list. The phone number fields show how to use the Django locale fields, and the email field shows it's purpose as well. The added_on field keeps track of when the person was added. One of the more interesting methods here has a @property decorator, a method would have worked fine as well. I choose to make this a property as I felt it is more of a property than a method. It also makes it easy to reference the same everywhere, in code and in templates.
  86.  
  87. from django import forms
  88. from people.models import Category, Person
  89.  
  90. class CategoryForm(forms.ModelForm):
  91.    class Meta:
  92.        model = Category
  93.        fields = ('title',)
  94.  
  95. class PersonForm(forms.ModelForm):
  96.    class Meta:
  97.        model = Person
  98.        fields = ('first_name', 'last_name', 'category', 'proximity', 'home_phone', 'cell_phone', 'email',)
  99.  
  100. The forms.py should be simple to grasp for most. It defines the forms and which fields from the database to allow the user access to. I didn't use excludes as when adding new fields later down the road, you may forget to exclude special fields you don't want visible. Forgetting to include won't lead to a security issue in special fields, but forgetting to exclude will. Keep that in mind.
  101.  
  102. from django.views.generic.list import ListView
  103. from people.models import Category, Person
  104. from django.views.generic.edit import CreateView, UpdateView, DeleteView
  105. from people.forms import CategoryForm, PersonForm
  106. from django.views.generic.detail import DetailView
  107. from django.shortcuts import get_object_or_404
  108. from django.core.urlresolvers import reverse
  109.  
  110. class CategoryMixin(object):
  111.     model = Category
  112.     def get_context_data(self, **kwargs):
  113.         kwargs.update({'object_name':'Category'})
  114.         return kwargs
  115.  
  116. class CategoryFormMixin(CategoryMixin):
  117.     form_class = CategoryForm
  118.     template_name = 'people/object_form.html'
  119.  
  120. class CategoryList(CategoryMixin, ListView):
  121.     template_name = 'people/object_list.html'
  122.  
  123. class CategoryDetail(CategoryMixin, DetailView):
  124.     pass
  125.  
  126. class NewCategory(CategoryFormMixin, CreateView):
  127.     pass
  128.  
  129. class EditCategory(CategoryFormMixin, UpdateView):
  130.     pass
  131.  
  132. class DeleteCategory(CategoryMixin, DeleteView):
  133.     template_name = 'people/object_confirm_delete.html'
  134.     def get_success_url(self):
  135.         return reverse('category_list')
  136.  
  137. class PersonMixin(object):
  138.     model = Person
  139.     def get_context_data(self, **kwargs):
  140.         kwargs.update({'object_name':'Person'})
  141.         return kwargs
  142.  
  143. class PersonFormMixin(PersonMixin):
  144.     form_class = PersonForm
  145.     template_name = 'people/object_form.html'
  146.  
  147. class PeopleList(PersonMixin, ListView):
  148.     template_name = 'people/object_list.html'
  149.  
  150. class ViewPerson(PersonMixin, DetailView):
  151.     pass
  152.  
  153. class NewPerson(PersonFormMixin, CreateView):
  154.     pass
  155.  
  156. class EditPerson(PersonFormMixin, UpdateView):
  157.     pass
  158.  
  159. class KillPerson(PersonMixin, DeleteView):
  160.     template_name = 'people/object_confirm_delete.html'
  161.     def get_success_url(self):
  162.         return reverse('people_list')
  163.  
  164. class ViewCategory(PersonMixin, ListView):
  165.     template_name = 'people/object_list.html'
  166.     def get_queryset(self):
  167.         self.category = get_object_or_404(Category, slug=self.kwargs['slug'])
  168.         return super(ViewCategory, self).get_queryset().filter(category=self.category)
  169.  
  170. Here are the CRUD views, I normally aways use classes rather than placing them directly into the urls.py, I do this so that I can easily extend the features of the class in the future if I need to, for example, using permissions and limiting a queryset. I choose to use a Mixin class to contain the models to make it more DRY. I could have also did the same with the forms, but I may wish to use a separate form to create and edit. For this example, the forms will remain the same. I also created two views which do the exact same thing to show how you can view a category.
  171.  
  172. Take notice in the various Mixins which have been created here. I did this to keep the code and templates more DRY, there is a separate Mixin class for each model, a form Mixin for each model as well. Depending on how you wish to display the Category model, there are 2 methods listed here. CategoryDetail has it's own template file and it needs to do a reverse relationship in order to function. The ViewCategory view looks a little more complex, but allows us to reuse the same template for PeopleList remaining more DRY at the template layer. Depending on your projects needs, choose one which suites your requirements, you will rarely need to use both methods, if ever.
  173.  
  174. from django.conf.urls.defaults import patterns, url, include
  175. from people.views import PeopleList, ViewPerson, NewPerson, KillPerson,\
  176.    EditPerson, ViewCategory, EditCategory, DeleteCategory, CategoryDetail,\
  177.    NewCategory
  178.  
  179. person_urls = patterns('',
  180.    url(r'^$', ViewPerson.as_view(), name='person_detail'),
  181.    url(r'^Update$', EditPerson.as_view(), name='person_update'),
  182.    url(r'^Delete$', KillPerson.as_view(), name='person_delete'),
  183. )
  184.  
  185. category_urls = patterns('',
  186.    url(r'^$', ViewCategory.as_view(), name='category_detail'),
  187.    url(r'^Alternate$', CategoryDetail.as_view(), name='category_detail_alt'),
  188.    url(r'^Update$', EditCategory.as_view(), name='category_update'),
  189.    url(r'^Delete$', DeleteCategory.as_view(), name='category_delete'),
  190. )
  191.  
  192. urlpatterns = patterns('',
  193.    url(r'^$', PeopleList.as_view(), name='people_list'),
  194.    url(r'^(?P<slug>[\w-]+).person/', include(person_urls)),
  195.    url(r'^NewPerson$', NewPerson.as_view(), name='person_add'),
  196.    url(r'^Categories$', CategoryList.as_view(), name='category_list'),
  197.    url(r'^(?P<slug>[\w-]+).cat/', include(category_urls)),
  198.    url(r'^NewCategory$', NewCategory.as_view(), name='category_add'),
  199. )
  200.  
  201. This describes how the URLs will route into our views. To keep things DRY, I used the include statement to include additional URLs. Without using the include, I would be repeating the slug capture numerous times for both the Person and Category views. This also shows that you can be as creative as you like with your URLs, I made these URLs descriptive and uncluttered. When using Class-based Views you should always pass the name keyword argument to the url statement, this will allow you to reference your views. Now onto the templates.
  202.  
  203. <html>
  204. <head>
  205.  <title>{% block title %}Untitled{% endblock %} | Phone Directory</title>
  206. </head>
  207. <body>
  208. <h1>Phonebook CRUD example!</h1>
  209. <a href="{% url 'people_list' %}">Index</a> | <a href="{% url 'category_list' %}">Categories</a> | <a href="{% url 'category_add' %}">Add Category</a> | <a href="{% url 'person_add' %}">Add Person</a>
  210. <hr/>
  211. {% block content %}
  212. The end user should never ever see this!
  213. {% endblock %}
  214. </body>
  215. </html>
  216.  
  217. This is the rather simple base.html for this example, it places some global links and has no styling. Notice how the global links are generated.
  218.  
  219. {% extends 'people/base.html' %}
  220.  
  221. {% block title %}{{object_name}} List{% endblock %}
  222.  
  223. {% block content %}
  224. <table>
  225. <thead><tr><th>{{object_name}}</th><th>Action</th></tr></thead>
  226. <tbody>
  227.  {% for object in object_list %}
  228.  <tr><td><a href="{{object.get_absolute_url}}">{{object}}</a></td><td><a href="{{object.get_update_url}}">Update</a> | <a href="{{object.get_delete_url}}">Delete</a></td></tr>
  229.  {% endfor %}
  230. </tbody>
  231. </table>
  232. {% endblock %}
  233.  
  234. This is the object_list.html template file, it provides a generic means of displaying a list object. For most projects you may wish to not use a generic list, as you may wish to provide additional information from the model. I did this in the example to keep it short and simple. You should also notice the methods from the model are being used here, and it works with all models that have these methods created. If these methods were not created, creating the action links would have been more difficult, and most definitely leading to more code. Model methods can do a lot, consider using it over a templatetag if you can.
  235.  
  236. {% extends 'people/base.html' %}
  237.  
  238. {% block title %}{{object_name}} Form{% endblock %}
  239.  
  240. {% block content %}
  241. <h3>{% if object %}Updating {{object}}{% else %}Add a new {{object_name}}{% endif %}</h3>
  242. <form action="" method="post">{% csrf_token %}
  243. <table>
  244. {{form}}
  245. </table>
  246. <input type="submit" value="Save {{object_name}}"/></form>
  247. {% endblock %}
  248.  
  249. Another example of using a generic template, this is the object_form.html template and should work for almost any ModelForm you give it. It allows you to quickly prototype the application's data components.
  250.  
  251. {% extends 'people/base.html' %}
  252.  
  253. {% block title %}{{object}}{% endblock %}
  254.  
  255. {% block content %}
  256. <table>
  257. <tr><th>Full name:</th><td>{{object.full_name}}</td></tr>
  258. <tr><th>Filed under:</th><td><a href="{{object.category.get_absolute_url}}">{{object.category}}</a></td></tr>
  259. <tr><th>Proximity:</th><td>{{object.get_proximity_display}}</td></tr>
  260. {% if object.home_phone %}<tr><th>Home Phone:</th><td>{{object.home_phone}}</td></tr>{% endif %}
  261. {% if object.cell_phone %}<tr><th>Cell Phone:</th><td>{{object.cell_phone}}</td></tr>{% endif %}
  262. {% if object.email %}<tr><th>Email:</th><td>{{object.email}}</td></tr>{% endif %}
  263. </table>
  264. <a href="{{object.get_update_url}}">Update</a> | <a href="{{object.get_delete_url}}">Delete</a>
  265. {% endblock %}
  266.  
  267. This is the person_detail.html template for displaying a single person in the database. It also has a cross-reference here to the Category it is part of.
  268.  
  269. {% extends 'people/base.html' %}
  270.  
  271. {% block title %}{{object_name}} Confirm delete?{% endblock %}
  272.  
  273. {% block content %}
  274. <h3>Are you sure you want to delete {{object}}?</h3>
  275. <form action="" method="post">{% csrf_token %}
  276. <input type="submit" value="Yes!"/>  <input type="button" value="No..." onclick="window.history.go(-1);"/>
  277. </form>
  278. {% endblock %}
  279.  
  280. This is the object_confirm_delete.html template which is displayed to the user when they would like to delete an object, again it is generic and should work for most models.
  281.  
  282. {% extends 'people/base.html' %}
  283.  
  284. {% block title %}{{object}}{% endblock %}
  285.  
  286. {% block content %}
  287. <table>
  288. <thead><tr><th>Person</th><th>Action</th></tr></thead>
  289. <tbody>
  290.   {% for object in object.person_set.all %}
  291.   <tr><td><a href="{{object.get_absolute_url}}">{{object}}</a></td><td><a href="{{object.get_update_url}}">Update</a> | <a href="{{object.get_delete_url}}">Delete</a></td></tr>
  292.   {% endfor %}
  293. </tbody>
  294. </table>
  295. {% endblock %}
  296.  
  297. This is the alternate method of displaying items in a Category, it uses a reverse relationship mechanic of Django to work.
  298.  
  299. There you have it, a complete Django CRUD example. This should show you how quick and simple it is to create data-driven applications in Django. This code could be much more simpler, but I wanted to be thorough and extend the classes to show what you can do.
  300.  
  301. Posted by Kevin Veroneau at 8:50 a.m.
  302. Tags: crud, database, django, model
  303. Home | Next tutorial in set
  304. Subscribe to: Tutorials (Atom)
  305.  
  306. May 23, 2013, 10:39 a.m. - TempppUser
  307.  
  308.     Hi, thank you for this tutorial. It is very useful for newbie like me :) May I ask you to attach project as archive, it will be better for using this code in own editor without entering all source code.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement