Let’s say you’re a PHP programmer (or ASP, or Java, or whatever) and you’re about to set sail on a new web app. One of the first things you’ll need is a database schema and some interface for simple CRUD (create, retrieve, update, delete) operations to work with your data. Maybe you’ll write some SQL CREATE TABLE statements. Maybe you'll install something like phpMyAdmin and use its web interface. One way or another, youre going to have to be able to work with that data as you build your app.
I’d like to propose an alternative. What if I told you you could write a Django model in less than an hour, and the result would be a fully-functional database, a production-ready, beautifully designed (as opposed that phpMyAdmin) CRUD interface, and you could still write your application login in PHP (or your perferred language)?
You can. Phil Dawes wrote about it at his blog today.
One of the core philosophies of Django is loose coupling. Besides the more alluring free-love connotation, this mean that each of the layers of Django’s “stack” ought to be independent of the others, such that you can choose to use only bits and pieces of it, and/or slide in other compenents if you prefer. Lucky you, it’s incredibly simple to learn the basics of Django’s model layer, which handles database schemas and object-relational mapping — even if you don’t know Python. Anyone can create a database schema in Django and get the crown jewel of the framework — it’s admin interface — with very little work, even if you plan to write the application logic itself in another language.
So let’s get started. Obviously you’ll need to install Django first. Once you’ve got that done, you’ll want to start a project and start an application within it. Let’s create a project called “news_cms” and a application called “stories.” At your ternmial prompt, just enter:
django-admin.py startproject news_cms
cd news_cms
django-admin.py startapp stories
That will create your basic project and application directory structure, along with a few inital files. In the news_cms directory, you'll find settings.py. You'll need to configure your database parameters here (database name, username, password, etc.), as well as a few other settings (the file is well-commented, so you can probably figure it out). Don't forget to add your new application, (i.e. news_cms.stories) to your INSTALLED_APPS setting. While you're there, you may want to go ahead and add django.contrib.admin to INSTALLED_APPS as well, since we'll need it a bit later. In the application directory stories, you'll have a new file models.py, which is where you'll create your database schema.
In models.py, you'll write Python classes for your data. Django's model API is very robust, and is also well-documented. Here’s an example model for our stories application:
from django.db import models
class Reporter(models.Model):
first_name = models.CharField(maxlength=30)
last_name = models.CharField(maxlength=30)
class Admin:
pass
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
class Article(models.Model):
headline = models.CharField(maxlength=100)
author = models.ForeignKey(Reporter)
body = models.TextField()
pub_date = models.DateField()
class Admin:
pass
def __str__(self):
return self.headline
We’re creating two distinct objects here: Reporters and Articles. Each article as a relationship (many-to-one, or ForeignKey) with a reporter. The def __str__ function returns the default string display of your object. With these 17 lines of code, Django will generate the necessary SQL to create the appropriate tables and run it aganist your database.
You’ll want to read the Django model documentation to learn about all the different field types that exist, as well as a plethora of optional attributes that can make the resulting admin interface even more interactive, accurate, and appropriate for your data.
Once you’ve got your model written, all you need to do to install it to your database is one simple command:
django-admin.py syncdb
Django models are very fast to write (especially if you use TextMate with the Django.tmbundle installed!). Once you get the hang of it, you can write even complex models in a matter of minutes. I recently wrote an entire reformulation of the iCalander specification as a Django model in about 30 minutes. I shudder to think how long the same thing would have taken me in SQL — and I wouldn’t have gotten the admin interface “for free.”
If you’ve got the Django admin application in your INSTALLED_APPS and uncommented the admin line in urls.py, you should be able to access the admin interface in your browser (typically at yourdomain.com/admin/). You'll find that your models have been installed and you've got the Wilson Miner-designed beauty of a UI for adding, changing, and deleting items from your database. It’s 100 times prettier than phpMyAdmin, and it’s actually usable by someone who isn’t a database guru. In fact, it’s designed for end users, not DBAs. You can filter, search, and tweak your data to your little heart’s content.
It’s really that simple to get yourself a lot less cruddy CRUD.
Obviously I’m a believer in the entire Django stack, so I whole-heartedly recommend you take a look at it and see what you think. But I also understand that you may already be a PHP expert, Java guru, etc. and you don’t want to take the time to learn Python just to get a nice admin interface. The beauty of this setup is that your data is just a standard PostgreSQL or MySQL database, and there’s absolutley no reason you can’t connect to it from whatever language you prefer to use for writing your app’s business logic. Have at it! Even if you only use the Django admin during development and build your own front-end to your data for the long, it’s still a great way to get at your data with very little effort and even less time.
And, if all goes according to my evil Django evangelism plan, you’ll soon be wanting to learn more about the framework that’s giving you such an ass-kicking admin interface for free. :)
Finally, here’s a great way to blow the mind of your new client: have a meeting with them and figure out what data they’re going to need on the site. Go back to your computer. Write the Django models and install them. Call the client back an hour later and tell them their admin area is ready and you’d like them to begin entering data. Not only does this impress the hell out of clients, but it gives you real data to work with as you develop their sites. Say goodbye to Lorem Ipsum and “Copy goes here.”
001 // Steven Ametjan // 07.14.2006 // 3:47 PM
You make a great argument, and as someone that works in a plethora of languages, this really makes a lot of sense. And as I continue to try and learn Rails, now that I have a fairly good grasp on Django, I doubt I’ll ever actually use Rails’ scaffolding, because it’s just too easy to use Django’s admin screens.
002 // Andrew // 07.14.2006 // 4:13 PM
Great thoughts. I considered this a few times though, I’ve adopted django where I would have previously used php. Perhaps an even better solution is to run the admin locally with the settings file pointing to your remote database. That way, it doesn’t matter if you can run python on your host (assuming you’re using shared hosting or something), but you still get absolutely all of the benefits of django’s admin.
003 // Jason Rutherford // 07.14.2006 // 4:18 PM
Too bad HostRocket sucks and I can’t use django/python with my server or else I’d be all over this.
004 // Jay // 07.14.2006 // 4:26 PM
This is exactly how I did http://coloradoridge.com/
They were not ready to do a full Django site, so we used Django for the admin tool and the rest of the site in php.
005 // matt // 07.15.2006 // 5:10 AM
is this really possible? how?
006 // Jeff Croft // 07.15.2006 // 2:18 PM
Matt-
It’s definitely possible to install Django on your local computer (so long as it meets the requirements…needs to have Python and Apache or lighttpd). Once Django is installed, it can be pointed to any database, local or remote, so it’s possible.
However, if you installed Django and ran the admin interface locally, only you would be able to get to it (which may be fine, depending on your needs). Also, your database would have to accept remote connections, and many hosting services don’t allow that.
But, if only you need to access the admin and your DB will allow remote connections, it’s definitely possible and it’s an interesting idea!
007 // Aidas Bendoraitis [aka Archatas] // 07.17.2006 // 4:13 AM
On one hand, the idea seems obvious, but on the other hand it is very original.
Anyway, this article is a smart way to force PHP developers to try Python and Django, so that they made certain themselves that development with Python makes much more satisfaction. :)
What is really good about this approach, that it is convenient to create a DB scheme using it and you don’t require a python hosting company to store you project. (I find the lack of Python hosting companies as the main reason for low Python’s popularity)
008 // mdh // 07.18.2006 // 6:56 AM
When setting up a model like this in django, can I sync it with an existing mySQL database? I have a existing application for which I’d like to have a nicer user interface to the database for a client. This sounds like an interesting option.
009 // Jeff Croft // 07.18.2006 // 9:11 AM
msh-
Django can do you one better than that, even. There’s an inspectdb command in which Django will actually look at your legacy database and generate a model file for you. You’ll probably want to tweak it some, especially adding the advanced admin options Django offers, but it will get you 90% of the way there. It’s documented here:
http://www.djangoproject.com/documentation/django_admin/#inspectdb
010 // Kevin Teague // 07.18.2006 // 10:34 PM
Django is great, especially the admin interface but I would quibble over the use of the term Louse Coupling.
Loose Coupling is a term used to describe the resiliency between computer systems: http://en.wikipedia.org/wiki/Loose_coupling
Being able to swap components in and out is called Modularity: http://en.wikipedia.org/wiki/Modularity_%28programming%29
011 // Jeff Croft // 07.18.2006 // 10:45 PM
Well, Kevin, you may be right in the most pedantic sense (at least Wikipedia says so), but I would respond in two ways:
I’m not really one to argue semantics, but I don’t see why it really matters whether you call it “loose coupling” or “modularity.” In the minds of most, they mean the same thing.
012 // Kevin Teague // 07.19.2006 // 12 AM
I had not seen the Coupling and Cohesion page, a comment on that page mentions that loose coupling as a term has been around for a while, and is meant in the way that Django is using it. There is a quote from Code Complete going back to 1993.
http://groups.yahoo.com/group/dpexplained/message/108
Wikipedia also mentions ‘loose coupling’ on their Coupling page:
http://en.wikipedia.org/wiki/Coupling%28computerscience%29
So Wikipedia also agrees with Django if you look on the right page :)
Anyways, the web services world uses the term loosely coupled a lot, so when I read the phrase I started thinking along the lines of XML, etc.
013 // IvanCamron // 10.14.2006 // 2:40 PM
“A pleasant experience is ahead: don’t pass it by.”acne solutionsleep aidhemorrhoids cure[link=http://www12.asphost4free.com/monicaocean]acne treatment[/link][link=http://www.blogging.co.uk/queenieflanders/]sleep aid[/link][link=http://clearblogs.com/lauriebank/]hemorrhoids cure[/link][url=http://www12.asphost4free.com/monicaocean]acne solution[/url][url=http://www.blogging.co.uk/queenieflanders/]sleep aids[/url][url=http://clearblogs.com/lauriebank/]hemorrhoid treatment[/url]
014 // Paul // 10.19.2006 // 2:27 PM
Somehow I missed this post the first time around (and seem to have arrived about the same time as the comment spammers).
Just wanted to pile on and say I too have been using Django in this way for many sites that I run which aren’t ready (for whatever reason) for a Django front-end yet. The inspectdb output is good enough in most cases, with a little tweaking, to run with. I’ve thrown away almost all of my homegrown PHP admin tools in favor of Django.
015 // Jewel Reithmeier // 12.15.2006 // 9:34 AM
The wisest mind has something yet to learn.
016 // Ben W. // 05.11.2007 // 11:02 AM
When I try running the admin section of the site
I get the login, but it is bare bones (no css, no images, etc.)
I am on WebFaction. How do I symlink the admin media files to my project/app?
017 // Jeff Croft // 05.11.2007 // 11:34 AM
@Ben: WebFaction’s great forum has a thread on exactly that topic.
018 // Rick Dooling // 11.24.2007 // 10:23 AM
Jeff,
This is the first tutorial I found for a news-like Django app. If it would be trivial could you continue on into the view and apps using Django and Python instead of php?
Thanks,
rd
019 // rajivbammi // 02.27.2008 // 6:29 AM
Hey Guys,
I got the idea but its not so clear..i m having an built in PHP application..how can i integrate it with Admin interface that i’ll create with Django??