Connect/Disconnect django signals

Posted: February 24th, 2010 | Author: | Filed under: Django | Tags: , , , , , , | No Comments »

Django signals allow to bind a function to a specific event.

There are 4 major signals available:

  • pre_save() ( before saving )
  • post_save() ( after saving )
  • pre_delete() ( before deleting )
  • post_delete() ( after deleting )

A simple example of connecting a signal:

# in models.py
from django.db.models.signals import post_save
from myapp.models import MyModel

def do_something(sender, **kwargs):
    # the object which is saved can be accessed via kwargs 'instance' key.
    obj = kwargs['instance']
    print 'the object is now saved.'
    # ...do something else...

# here we connect a post_save signal for MyModel
# in other terms whenever an instance of MyModel is saved
# the 'do_something' function will be called.
post_save.connect(do_something, sender=MyModel)

If you need to disconnect/detach a signal:

# instead of connect() we call disconnect()
post_save.disconnect(do_something, sender=MyModel)

Get/List model fields

Posted: February 22nd, 2010 | Author: | Filed under: Django | Tags: , , , , , | 8 Comments »

It is possible to get/list all of the fields for the given model, to do so you need to access the _meta attribute of the Model.
The following example demonstrates how to do it.


# in the models.py
class Car(models.Model)
    year = models.IntegerField()
    name = models.CharField(max_length=50)
    ...

    def get_fields(self):
        # make a list of field/values.
        return [(field, field.value_to_string(self)) for field in Car._meta.fields]

Now that we implemented the get_fields function for our Car model, we can use this in the template…

# your template file...
# I assume that the variable 'car' is an instance of Car object.
{% for field, value in car.get_fields %}
    {{ field }} : {{ value }}
{% endfor %}

Session array/list append does not work

Posted: February 1st, 2010 | Author: | Filed under: Django | Tags: , , , | 5 Comments »

I was trying to save and update some arrays inside the Django session object but it was not working at all…

The following snippet DOES NOT WORK

request.session['array'] = [] # let's create an empty array
# try to append some integers...
request.session['array'].append(1)
request.session['array'].append(2)
request.session['array'].append(3)
...

In order to solve this we need to store the array in a temporary object first.
Quick fix:

request.session['array'] = []
tmp = request.session['array']
tmp.append(1)
tmp.append(2)
tmp.append(3)
request.session['array'] = tmp # this works now.
...

Django and mod_wsgi deploy example

Posted: January 13th, 2010 | Author: | Filed under: Django | Tags: , , , , | No Comments »

So what do we do next when we finished to develop(debug, debug… debug…!) our application? We go and deploy it of course!
Well, a common choice of deploying Django application is to use Apache httpd and mod_wsgi.

Let’s suppose the following scenario:

  • our application name is marina
  • our application is placed inside /home/ directory
  • our static files (javascript, images, css etc…) are inside /home/marina/media/

The first step is to create the WSGI file and place it inside /home/marina/
With the following content:

#!/usr/local/bin/python
import os, sys
sys.path.append('/home/')
sys.path.append('/home/marina/')
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'  # this is your settings.py file
os.environ['PYTHON_EGG_CACHE'] = '/tmp'

import django.core.handlers.wsgi

application = django.core.handlers.wsgi.WSGIHandler()

The second step is to edit your httpd.conf and add the following lines.


<Directory "/home/marina/media">
   Order deny,allow
   Allow from all
</Directory>

<Directory "/home/marina">
    AllowOverride All
    Order deny,allow
    Allow from all
</Directory>

Alias /media/ /home/marina/media/
ServerAdmin admin@djangofoo.com
ErrorLog "logs/marina.com-error_log"
CustomLog "logs/marina.com-access_log" common
# mod_wsgi configuration is here
# we are running as user/group 'deamon', if you don't have those you need to change or create.
WSGIDaemonProcess marina user=daemon group=daemon processes=2 threads=25
WSGIProcessGroup marina
# this is our WSGI file.
WSGIScriptAlias / /home/marina/marina.wsgi

We need to be sure that our folder is readable by the ‘daemon‘ user

chown -R daemon /home/marina

NOTE: if you are using /media/ to store all the static files be sure you have this inside your settings.py

ADMIN_MEDIA_PREFIX = '/admin_media/' # by default this is /media/ which conflicts with our /media/ !!

And finally don’t forget to restart your apache.

If you still have issues to run a Django application its worth checking the error logs.


Display asterisks for required fields in template

Posted: January 11th, 2010 | Author: | Filed under: Django | Tags: , , , , | 2 Comments »

If you want to display simple asterisks (*) for required fields in Django then the following code is for you.
The trick is to access the field properties inside the template and make a conditional statement.
Here is a simple example of view and template:

# this is inside your views.py
def do_something(request):
      """Display simple form"""
      form = MyForm() # this will be used in the template.
      return render_to_response('template.html', locals())

# this is inside your template.html
{% for field in form %} {{ field }} {% if field.field.required %}(*){% endif %} {% endfor %}

The locals() function is a built in python function