a blog about programming, photography and electronics.

Tip – Dynamic Path For FileField

Posted: June 15th, 2010 | Author: | Filed under: django, tips | Tags: , , | No Comments »

In a recent project I needed to save a file to a dynamic directory.

My model was something like this:

from django.db import models
 
class MyDoc(models.Model):
    name = models.CharField()
    document = models.FileField(upload_to='uploads/documents')

with this code each document will be uploaded to MEDIA_ROOT/uploads/documents.
In order to upload the file to a dynamic dir like this: MEDIA_ROOT/uploads/documents/id/ I used this code:

from django.db import models
 
class MyDoc(models.Model):
    upload_to = 'uploads/documents/%d/%s'
 
    def _get_upload_to(self, filename):
        return self.upload_to % (self.pk, filename)
 
    name = models.CharField()
    document = models.FileField(upload_to=_get_upload_to)

That’s all (Thats’s Django!), now this code will upload each document into a separated dir for each object.

UPDATE
The code I posted before doesn’t work properly in fact the first time we save the model the pk is None so this code can’t get the correct path.

If you have any question, please feel free to ask.


Adding additional views to django admin

Posted: May 17th, 2010 | Author: | Filed under: django | Tags: , | 2 Comments »

Today I wanna show you a simple way to add an additional view to the admin site.
Imagine that you want to create a view to review a model, something like send an email to the site owner with your thoughs (or your changes) about an entry.

First we need to define a simple model (of course you can use your existing model):

from django.db import models
 
class MyEntry(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()
 
    def __unicode__(self):
        return self.title
 
    class Meta(object):
        verbose_name = 'My Entry'
        verbose_name_plural = 'My Entries'

Read the rest of this entry »