Entries Tagged 'django' ↓

Breaking Apart Models in Django

Depending on the size of your models.py, you may find it becoming unwieldy, especially if you are on a team with multiple developers are editing the same file, increasing the odds for merge conflicts.

There are two parts to breaking up a large module in Django. The first is a purely Python convention where you break apart the file into multiple files and create a subdirectory for the name of the original module so your models.py file becomes:

models/__init__.py
models/module1.py
models/modlue2.py

Inside your __init__.py you’ll want to import from your module1.py and module2.py modules and add those imported objects to __all__:

# __init__.py
from app.models.module1 import MyClass
from app.models.module2 import AnotherClass, function_one
__all__ = ['MyClass', 'AnotherClass', 'function_one']

Now that you have taken care of the Python part of this exercise, you’ll need to do a couple tricks to get your models importing properly in the context of your django project.

It involves adding a couple o attributes to the Meta inner class. Thanks to Collin Grady (aka Magus on #django on irc.freenode.net) for pointing these tips out to me:

class MyClass:
    ...
    class Meta:
        app_name = 'myappname'
        db_table = 'myappname_myclass'

Now you should have a better code base that causes less contention and makes it faster to locate the models you are looking for.

Update

As has been pointed out to me in the comments as well as one #djano today, I got “Empty” and “Magus” mixed up with their real names. Much apologies for any and all confusion this might have caused.

Update 2

As pointed out in some of the recent comments below, this post was corrupted when I enabled the markdown plugin for wordpress. It is treating all posts I have ever written as markdown which is not right but I have not the energy nor the inclination to go back in time and update all my old posts. That being said, I really love markdown for my posting so I’ll keep the plugin activated.

Django Flatpages with Debug Set to False

After deploying a site I am working on to a preview server running apache/mod_python, it was the first time serving up the site in something other than python manage.py runserver.

I worked through a number of issues that I found quick answers for on the FAQ site for django, but one in particular I couldn’t figure out, but eventually got pointed to the obvious in the irc channel for django.

The site has a number of flatpages, which I have come to learn is a middleware trick where when a url doesn’t match anything and right before a 404 normally would be thrown giving the Page Not Found error, it checks against any flatpage “urls” you have registered the database with static content. If it finds something it will return that content, if not the 404 bubbles back out of the middleware and goes to the user.

Everything worked fine with DEBUG=True in my settings.py file. However, when I changed it to DEBUG=False, I got a 500 Internal Server Error but then when I looked at my error.log, I could see a django exception saying it couldn’t find the 404.html.

This made no sense to me at all. Why would it be looking for a 404.html when it doesn’t need it yet (the flatpage middleware should have intercepted it before it looked for a 404.html template, was my thinking). It was suggested to me in the irc channel that I create a 404.html (for more reasons that just fixing this problem).

So to just test that theory, I ran touch templates/404.html — it worked!

Django Custom Filter Registration

I wrestled with this one for about an hour last night before realizing it was rather simple. Following the instructions to create a custom template filter, I thought everything was simple and made since until when I tried to load the page to test it.

The page spewed a stack trace telling me that it couldn’t find the custom filter I was trying lo load with:

{% load website.app.custom_filters %}
{% filter htmlcompress %}

{% endfilter %}

I then realized that I had registered it like so:

website/app/templatetags/customfilters.py

from django import template
register = template.Library()
@register.filter(”htmlcompress”)

It seems that there is some magic that occurs that loads the custom_filters.py module in a global namespace so that doing this in my base template works:

{% load custom_filters %}
{% filter htmlcompress %}

{% endfilter %}

Thought I’d post this in case I am not the only new person to django wrestling with this.

Running Multiple Django Versions in Development

I have needed to use different revisions of the django trunk at different points in time (in testing locally a new revision before upgraded in production, or working on two different projects that deploy to two different production environments, etc).

There may be a better way, but how I have handled it pretty painlessly is by running this script:

!/bin/bash

rm -rf /[YOUR PATH]/$1 svn co -r $1 http://code.djangoproject.com/svn/django/trunk/django /[YOUR PATH]/$1 sudo rm -rf /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django sudo rm /usr/bin/django-admin sudo ln -s /[YOUR PATH]/$1/ /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django sudo ln -s /[YOUR PATH]/$1/bin/django-admin.py /usr/bin/django-admin echo “Switched to” $1

It takes a single parameter, a revision number.

./switch.sh 7000

I run this script from within a directory in my home directory called “django”.

You will likely need to change the paths in the script above if you are not running Python 2.5 on Mac OSX. Also, remember to substitute “[YOUR PATH]” for the base location of where you want to store the django code.

Cool Django Apps / Frameworks / Add-Ons

Ran across three really cool looking extensions to django:

  • databrowse
    Databrowse is a Django application that lets you browse your data.

    As the Django admin dynamically creates an admin interface by introspecting your models, Databrowse dynamically creates a rich, browsable Web site by introspecting your models.
  • sitemap
    Django comes with a high-level sitemap-generating framework that makes creating sitemap XML files easy.
  • webdesign
    The django.contrib.webdesign package, part of the “django.contrib” add-ons, provides various Django helpers that are particularly useful to Web designers (as opposed to developers).

I am anxious to given these items a spin, especially databrowse.

Django Fixtures and Flatpage Deployment

I was introduced today to the concept and django feature known as Fixtures, while reading my dead-tree version of the new django book.

I am currently building a small site, fairly simple and mostly static. I have written an app that is my own take on the flatpages that are in django.contrib (a post on this later) — I basically needed a little more flexibility for different islands of content.

In building this site and setting up the appropriate flatpages in my development, I realized that I am going to need to seed the database when I release to production or else there are going to be a lot of 404 errors. Also, since the pages are referred to in my menus, I need for the url on the flatpage model to be exact. It’s not that many pages, but still, I thought, there had to be a better way that either manually hand entering all the data, troubleshooting 404s for typos in the url field, or doing any manual exporting of data at the mysql prompt.

As if by some divine revelation, I happened across the chapter in the book talking about django-admin dumpdata/loaddata. What’s cool about this is by dumping the data into a file in source control, you can revision your flatpages (or any other data that is).

Here’s what I did:

mkdir fixtures

django-admin dumpdata flatpages –indent=4 > fixtures/flatpages.json

Remember, I have a local app in my project called flatpages that is my replacement for the contrib version.

I tested that this data was usable by changing my setting.py file to use a different database (a new one):

mysql

mysql> create database test_import; msyql> exit; django-admin loaddata fixtures/flatpages.json python manage.py runserver

Then fired up the browser and there was all my flatpages, perfect!