post

Cleaning your database and starting over in Django

I haven’t posted any django information in a while because I haven’t had any time to mess with it. Today, I dove back in.

I wanted to get a fresh start with the project I’m working on so I thought I’d clear out the database. Why for the life of me I couldn’t find the proper incantation to make this happen I’ll never know.

After searching for about 10 minutes I found it. I’m posting it here so I can reference it the next time I have a brain lapse.

Are you ready? Here it is…
manage.py flush

This will reset the database to the state immediately after it was created.

post

Web Framework Django has a new Book

Fans of the excellent Python based web application framework Django will be happy to find out that Christmas has come early this year. Apress has just published The Django Book. Every good framework needs excellent documentation in order to break through. It’s a sign that the software has come into it’s own. Django is no exception.

The Django Book was published by Apress in December 2007. It covers the most current version of Django (as of this writing). It is available in hard copy from your favorite book seller on you can read it free online at the Django Book website. I’ve used this book in BETA form for the last four months. The final version exceeds the beta in quality and depth.

[tags]python,framework,django,documentation[/tags]

Powered by ScribeFire.

post

Adding Model Field Validation to the Django Admin Page

Django, the hot Python web application framework, provides an excellent administration user interface out of the box. Django originated in the newsroom and it’s reflected throughout the code. The idea behind including an admin interface is that reporters can work on easily submitting their content while the code jockeys work on the fun stuff – namely presenting that content to their readers.

The admin interface provides a great experience out of the box but is also extensible so you can add features not present in the original interface.

I was working on a Model that was meant to be manipulated inside the admin interface. I wanted to provide constraints on some Integers Fields in that that model in order to limit the range of possible entered values.

The first way I tried to solve this was to add a choices parameter for my IntegerFields. While this technique worked, it caused my admin interface to add a drop down box displaying my choices. This was not what I was looking for.

The final way I solved it came from a suggestion on the Django IRC channel. Use validators. It took some digging through the documentation but I figured out how to do what I want. I will explain by way of an example.

from django.core import validators
from django.db import models

range_validator = validators.NumberIsInRange(0,4)

class Test (models.Model):
    valid_int = models.IntegerField(null=True, blank=True, validator_list=[range_validator])

The validation framework is defined in the validators module. Import that if you need to perform any validation on your data.

Django includes a number of built-in validators. I lucked out and they had a validator that suited my purposes. The first step creates a validator instance of NumberIsInRange with the appropriate range. This returns a callable that I use later.

Model fields take a parameter of type validator_list which is a “list of extra validators to apply to the field. Each should be a callable that takes the parameters field_data, all_data and raises django.core.validators.ValidationError for errors. (See the validator docs.)”

A quick test in the admin interface and the code works.

The Django documentation contains everything you need to get the job done. Some careful searching and a great support community has helped make Django one of the best web frameworks available.

[tags]django,framework,tutorial[/tags]

post

Django Tip – Don’t use hard coded urls in templates

Django, the Python based web framework has a template system which allows you to separate business logic from presentation. It provides a method of substituting variables inside the template using the {% var %} syntax.

One of the things you will often need to do is provide links to various views inside your application. However, the worst possible way to do this is to hard code pages inside your template. Developers of the Django framework are proponents of the DRY philosophy. This is evident in the URL mapping mechanism.

When you need to link to other views in your application, open your urls.py file. Copy the full package.app.view.view_name to your view. Then, inside your template in an anchor tag insert the following.

<a href="{% url package.app.view.view_name %}">
Link location
</a>

Django will then substitute the view name with the proper link relative to where your application lives.

The obvious advantage to doing this is if you ever publish your Django application to a different location you don’t have to update your links.

[tags]Django,tutorial[/tags]

post

Running external scripts against Django Models

Django, the Python based web application framework, is an excellent Model/View/Controller application framework for rich website design.

A Django application runs under a web server. However, often it is necessary to develop external scripts that need to interact with you web application data models. This brief tutorial will walk through an example. This may not necessarily be the _best_ way to do this, but merely a way. I struggled for a few hours on this last night and thought it would be useful to others to document my results.

Let’s look at an example. Feel free to take this and modify it as needed. It’s a bit contrived but will suit our purposes.

Suppose you have written a blog application and you want to periodically purge old entries. In your Model, you have written code to to all of the heavy lifting. Now, you want to make sure that these updates happen at a scheduled interval.

Assume your project lives in c:\project\blogprj

import sys,os
from datetime import *
sys.path.append('c:\\project')
os.environ['DJANGO_SETTINGS_MODULE'] ='blogprj.settings'

from django.core.management import setup_environ
from blogprj import settings

from blogprj.blog.models import Entry

setup_environ(settings)

blogs = BlogEntry.objects.all()

for entry in blogs:
     entry.purge_oldentries(date.today())

Let’s take a closer look at this.

sys.path.append('c:\\project')

This line appends your project directory to the python module search search path so that it can find the your packages. Remember, when django creates your template, it creates an __init__.py file in each directory of your project and apps. These __init__.py files tell python to treat the entire directory as a python package. If you set your module path to c:\\project\\blog then python will not be able to find the root of your packages (blog)

os.environ['DJANGO_SETTINGS_MODULE'] ='blogprj.settings'
The DJANGO_SETTINGS_MODULE variable tells your django application the name of the settings module. It uses the Python path syntax.

from django.core.management import setup_environ
from blogprj import settings

Since you are using Django libraries, you must tell it where to find your settings.py file. This is done through the function setup_environ and your project settings, imported here.

from blogprj.blog.models import Entry

We are going to be working with the Entry model, so we need to import it.

setup_environ(settings)

As stated previously, we must tell Django to use our project settings. This is necessary so Django can know what database we use, our installed apps, etc. This is handled by the setup_environ() method which takes a Settings object as a parameter.

Once this is done, the rest of the application merely performs the work against the model.

Save this script and you can run it inside your favorite scheduler, on Windows, we use Task Scheduler.

I hope this small tutorial has given you a little insight in how to call Django from external scripts. I welcome your comments.
[tags]Django, Development, Python, tutorial[/tags]