I’m excited about my new admin interface. Page 2 on the tutorial goes into how to customize the admin. I don’t care about that at the moment so I go to page 3.
Page 3 is about URLs. Django uses a sequence of tuples populated with regular expression -> url maps. Great, this is how I did things in PHP. I add a couple of URLs and move on.
Next it’s time to create my views. I write my first view which simple prints “Hi!”. It works, great. I see that the basics of the template language used in Django are very similar to how I do it in PHP. I port my view from my PHP template to the template in Django.
{% foreach company in category.company.all() %}
Unfortunately this doesn’t work. It’s not looping over my categories/companies/videos. I think it’s because it’s having trouble going backwards with my foreign key relationships.
I find that in order to go backwards you have to do this
{% for company in category.company_set.all() %}
You have to use _set to access foreign key items. This doesn’t work either! I give up on this route and I try the method I use in PHP… creating a giant multi-dimensional array and then looping over that.
This is where I hit a wall. I quickly find out that Python’s version of arrays, called dictionaries, can’t be created like they can in PHP. I don’t like that one bit.
Python doesn’t have a version of
$video['company_id']['category_id']['video_id']['name'] = 'Video Name';
I find some custom classes via google, but Django won’t iterate over them. A couple hours later I figure I need help. I ask a couple of places and everyone suggests that it is possible with Django’s ORM, I just need to remove the ()
I find that you have to do this!
{% for company in category.company_set.all %}
You have to remove the () for functions that have no arguments. Works like a champ. Two minutes later I have all categories/companies/videos displayed correctly. I’m still using Django’s development server though so I have no styles/images, just black test on a white background.
I read somewhere that I should be using mod_wsgi instead of mod_python (I can’t find the source). Using this I get it working with Django pretty quickly.
Good:Django’s ORM
Bad: Python’s dictionary handling not my favorite. I enjoy the way PHP has implemented arrays and how they can be used as lists, dictionaries, stacks, etc. Django’s documentation is thorough, but I get lost in the maze of versions it has.
Notes: I don’t know why I didn’t think of this, but it’s been pointed out to me that you can do this:
a = dict() a['foo'] = dict() a['foo']['bar'] = {'this works': 'yes it does'}
That probably would have solved my problem.