shabda
Comments
Reactions

Wordpress and Django: best buddies

By : Shabda Raaj

Summary: How to integrate a non Django database system in your Django code, using Wordpress as example. The completed code is available at github or you can see some screnshots


Though there are quite a few good Django blog applications, our blog is based on Wordpress. A number of plugin's make moving to a Django based app a bad decision for us, and not in the spirit of "best tools for the job".

We moved the other way, and decided to use Django to admin the Wordpress database. The completed code is available on Github

It is not too hard, with the the builtin Django commands. Django provides the inspectdb command which allows you to build your models.py from an existing non Django database.

Here we will see the steps followed for Wordpress, but it would be about the same for all systems.

Take a back up of wordpress
mysqldump -u wordpress_user -p --database wordpress_database > data.sql
Create a new project, and set its settings to use the Wordpress database.
    DATABASE_ENGINE = 'mysql'           # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
    DATABASE_NAME = ''             # Or path to database file if using sqlite3.
    DATABASE_USER = ''             # Not used with sqlite3.
    DATABASE_PASSWORD = ''         # Not used with sqlite3.
    DATABASE_HOST = ''             # Set to empty string for localhost. Not used with sqlite3.
    DATABASE_PORT = ''             # Set to empty string for default. Not used with sqlite3.
Get the initial models.py
./manage.py inspectdb > models.py

This will create all the database tables in a form Django can understand. Here is what this command creates for a my Wordpress installation with the YARPP plugin. http://gist.github.com/278962

Create a new app and put this models.py there.

With this done, you can treat the non Django part as a standalone application. Since Wordpress appends all its table with wp_ prefix, we name this applications wp to maintain table name compatibility with Django naming conventions.

You will notice that all models have the db_table populated, so we can rename tables, without changes to the database.

Differences between Wordpress and Django style naming.

At this point you will notice some differences in how Django names things (in a best practice sort of way), and how Wordpress does it.

a. Django table and model class name are (generally) singular. eg class Post(models.Models) leads to table app_post. Wordpress tables are (most of them) named plural eg wp_posts.

b. Django attributes are generally named without the table name part. Eg

class Comment(models.Model):
    author_name = models.TextField()
    content = models.TextField()

Wordpress is explicit here and includes the table prefix with attributes.

mysql> desc wp_comments;
+----------------------+---------------------+------+-----+---------------------+----------------+
| Field                | Type                | Null | Key | Default             | Extra          |
+----------------------+---------------------+------+-----+---------------------+----------------+
| comment_ID           | bigint(20) unsigned | NO   | PRI | NULL                | auto_increment | 
| comment_post_ID      | bigint(20) unsigned | NO   | MUL | 0                   |                | 
| comment_author       | tinytext            | NO   |     | NULL                |                | 
| comment_author_email | varchar(100)        | NO   |     |                     |                |

.....

I believe this is due to the way you would generally be using the code. In Django you would do comment.author where being explicit doesn't add any value, while in Wordpress, you would use, select comment_author, post_title ... from wp_comment, wp_post ... where join, where being explicit is useful.

You can decouple the Django and database names by using the db_table and db_column attributes. We choose to rename the Class names to match Django conventions while we let the column names remain the same.

Add Admin and other Django niceties.

Wordpress doesn't (seem to) have foreign key constraints setup correctly, and uses bigint(20) unsigned without foreign key constraints to refer to referred entities. This means Django creates all ForeignKeys as IntegerFields.

Modify them to use ForeignKey instead. Also add __unicode__, to your classes.

Add an admin.py to register all your classes.

And you are done! Now you can access, and work with your Wordpress data inside Django and Django admin.


There are a few more things which will allow a easier Wordpress setup.

Create template tags to show the latest posts and comments.
@register.inclusion_tag("wp/recent_posts.html")
def show_posts(num_comments):
    return {"posts": Post.objects.filter(post_type="post", post_status="publish").order_by("-post_date")[:num_comments]}

So you can see that there is nothing Wordpress specific we need too do here.

Create a better admin.
Add ModelAdmin to generally used models.
Allows accessing attributes via the Django style names.

If you override __getattr__, you can access the attributes via other names. Eg in the current setup you need to do comment.comment_content, comment.comment_author etc, while we would like to do comment.content and comment.author as a shortcut.

class WordPressModel(object):    
    def __getattr__(self, v):
        if v in self.__dict__:
            return self.__dict__[v]
        else:
            new_v = "%s_%s" % (self.__class__.__name__.lower(),  v)
            if new_v in self.__dict__:
                return self.__dict__[new_v]
            else:
                raise AttributeError

It is highly debatable whether this is a good idea :), but it is too convenient right now not to test this method out.

Here are some screenshots.


Do you subscribe to our feed? We recently made a full text feed available, so if you are using the old feed, you should change it. Subscribe now.


Related Posts


Can we help you build amazing apps? Contact us today.

Comments

NothingToLose

Rather cool site you've got here. Thanks for it. I like such themes and everything connected to this matter. I would like to read a bit more soon.

Best regards

commmenttor
Gus 17th March, 2010

Why would you do that? Why would you want to admin a wordpress blog through Django? I thought you were going for authentication/single signon... What's the point?

commmenttor
Oli Warner

This is awesome.

In answer to the second comment (from Gus), here's my scenario: I have a client who is addicted to Wordpress. They will only use WordPress but PHP (more php-fcgi) is a complete pig when it comes down to system resources. Django is not a pig. Django is a hundred thousand times faster at pushing things out and uses so many fewer resources in the process.

By giving Django access to the WordPress data you are able to keep wp-admin around (a single user meaning you only need a couple of php-cgi processes) and you can serve the frontend completely through Django. Yes it requires some work and yes, you lose a lot of wordpress features (themes, plugins, comments, etc - all of which can be re-engineered) but you keep wp-admin, its biggest asset.

commmenttor
pspin6

good post ,thanks

commmenttor
Ryan

Very nice, thanks for the tip!

commmenttor
It optimering

Your blog is well maintained…..

commmenttor
Family Lawyer Brampton

Good ideas! I like the way you express your idea and the topic you choose. KEep on your sharing.

commmenttor
Rylie 7th April, 2012

Fyi, your screenshot images in this post are broken.

commmenttor
Burberry T-shirts pour aimer la mode Messieurs et les femmes

Wordpress and Django: best buddies - Agiliq Blog | Django web app development

commmenttor

Reactions

uswaretech_blog

Wordpress and Django: best buddies: Summary:
How to integrate a non Django database system in your Django code, us… http://bit.ly/4YdzbE

This comment was originally posted on Twitter

DjangoIreland

Wordpress and Django: best buddies — The Usware Blog – Django Web … http://bit.ly/71FUdA

This comment was originally posted on Twitter

planetdjango

Wordpress and Django: best buddies http://goo.gl/fb/mdbG #django

This comment was originally posted on Twitter

clubwordpress

#WordPress and Django: best buddies — The Usware Blog – Django Web … http://bit.ly/8vDzPW

This comment was originally posted on Twitter

allWordpress

Wordpress and Django: best buddies — The Usware Blog – Django Web … http://bit.ly/8vDzPW

This comment was originally posted on Twitter

onion_papa

http://tinyurl.com/yd2fymo
Wordpress and Django: best buddies — The Usware Blog – Django Web Development

This comment was originally posted on Twitter

diegueus9

Wordpress and Django: best buddies http://bit.ly/647lJZ

This comment was originally posted on Twitter

djangobot

Shabda Raaj: Wordpress and Django: best buddies http://bit.ly/8UtvVT

This comment was originally posted on Twitter

dartdog

Intriguing concept? Wordpress and Django: best buddies http://goo.gl/fb/mdbG #django

This comment was originally posted on Twitter

uswaretech

http://bit.ly/5EHdE6 Wordpress and Django: best buddies.

This comment was originally posted on Twitter

grameensol

Wordpress and Django: best buddies — The Usware Blog – Django Web Development http://bit.ly/8vDzPW

This comment was originally posted on Twitter

ePerception

Wordpress and Django: best buddies — The Usware Blog – Django Web … http://bit.ly/8vDzPW

This comment was originally posted on Twitter

djangostories

Wordpress and Django: best buddies: http://bit.ly/7TVC6I

This comment was originally posted on Twitter

scottcom

Wordpress and Django: best buddies — The Usware Blog – Django Web … http://bit.ly/4×0O7e

This comment was originally posted on Twitter

wpbjorn

#wordpress and Django: best buddies — The Usware Blog – Django Web Development http://bit.ly/6aEWVc

This comment was originally posted on Twitter

djangostories

Wordpress and Django: best buddies — The Usware Blog – Django Web Development: http://bit.ly/5cXG6G

This comment was originally posted on Twitter

djangostories

Wordpress and Django: best buddies: http://bit.ly/7JkWK6

This comment was originally posted on Twitter

cistyle

Wordpress and Django: best buddies — The Usware Blog – Django Web …: About Us · Blog · Contact Us · Home · Subsc… http://bit.ly/5O84M3

This comment was originally posted on Twitter

siliconchaos

Wordpress and Django: best buddies http://bit.ly/57mbfp

This comment was originally posted on Twitter

kozo_ni

Wordpress and Django: best buddies http://uswaretech.com/blog/2010/01/wordpress-and-django-best-buddies/

This comment was originally posted on Twitter

OpenIndex

Ich wusste garnicht, dass #Wordpress und #Django so gut befreundet sind ;) » http://bit.ly/5ZZu2P

This comment was originally posted on Twitter

AntoineLeclair

@laurent Si tu veux combiner les 2 http://is.gd/6weBg #wordpress #django

This comment was originally posted on Twitter

bcurtu

Wordpress and Django: best buddies http://bit.ly/8vDzPW

This comment was originally posted on Twitter

marcboivin

Lifelong dream: http://bit.ly/4AnQI7

This comment was originally posted on Twitter

mariocesar_bo

Wordpress y Django grandes amigos :-) http://bit.ly/7UD1oi

This comment was originally posted on Twitter

kocinetwork

[from sjwilliams] Wordpress and Django: best buddies — The Usware Blog – Django Web Development: http://bit.ly/8vDzPW

This comment was originally posted on Twitter

DaNmarner

GR [Wordpress and Django: best buddies] http://j.mp/8JGxkj

This comment was originally posted on Twitter

purplehayz

#Wordpress and #Django: best buddies http://is.gd/6HYac

This comment was originally posted on Twitter

cooltheme

Wordpress and Django: best buddies — The Usware Blog – Django Web … http://bit.ly/56bwNj

This comment was originally posted on Twitter

wpdaily

Wordpress and Django: best buddies — The Usware Blog – Django Web … http://bit.ly/7gbPNS

This comment was originally posted on Twitter

dawnsjewelry

Wordpress and Django: best buddies — The Usware Blog – Django Web …: Summary: How to integrate a non Django d.. http://bit.ly/8vDzPW

This comment was originally posted on Twitter

pacorro2000

http://icio.us/kxc2rv

This comment was originally posted on Twitter

junysb3

Wordpress and Django: best buddies - The Agiliq Blog: http://bit.ly/e7jwKK

commmenttor
© Agiliq, 2009-2012