Thursday, May 13, 2010

Modular Django Admin Part 1

The django admin is awesome, we all know that, but there is always the debate to role your own or to customize the admin. Make the admin more modular would be ideal and that is what we will be trying to do.

In part one we will just start with the basics and setup a tabular list using the object_list generic view with gives you pagination for free.

One trick to get the key/value pairs into the template of the model is using a function to return self.__dict__.iteritems()

The Model (myapp/

class MyObject(models.Model):
    name = models.CharField(max_length=75)
    slug = models.SlugField(unique=True)
    def __unicode__(self):

    def attrs(self):
        for attr, value in self.__dict__.iteritems():
            yield attr, value

The View (myapp/

from django.views.generic.list_detail import object_list
def applicant_list_jobs(request):
    return object_list(request, queryset=Job.objects.all(), paginate_by=5)

The Template (templates/myapp/myobject_list.html)

{% extends "admin/change_list.html" %}
{% block content %}
  {% for object in object_list %}
  <tr class="{% cycle 'row1' 'row2' %}">
   {% for key,value in object.attrs %}
   <td>{{ value }}</td>
   {% endfor %}
  {% endfor %}
 <p class="paginator">
 {% if page_obj.has_previous %}
  <a href="?page={{ page_obj.previous_page_number }}"><</a>
 {% endif %}
  Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}
 {% if page_obj.has_next %}
  <a href="?page={{ page_obj.next_page_number }}">></a>
 {% endif %}
{% endblock content %}

Next up will be where the templates and urls go for login and the built in authentication tools.

No comments: