Benvenuto nel mio blog.
Gli articoli sono ordinati secondo tre livelli: base, medio e avanzato. Il livello medio è per chi utilizza Linux o che non ha paura di provare cose nuove. Avanzato è dedicato ai programmatori o comunque agli informatici con esperienza. Il livello base è utilizzato in tutti gli altri casi.

martedì 18 luglio 2006

Create an image model for your photos in Django with multiple categories

I write this post because Django documentation is not exhaustive for the ImageField.

Create an application in your project with:

$ python manager.py startapp photos
You can use what application name you like.

Then create the directory "photos" in your media directory.

Enter in the application directory and edit the models.py file:

from django.db import models

class PhotoCategory (models.Model):
name = models.CharField(maxlength=32)

def __str__ (self):
return self.name

class Admin:
pass

class Meta:
verbose_name_plural = 'photo categories'

class Photo (models.Model):
description = models.CharField(maxlength=128)
pub_date = models.DateField('Publication date', core=True, auto_now_add=True)
category = models.ManyToManyField(PhotoCategory, verbose_name=_('photo categories'), blank=True, filter_interface=models.HORIZONTAL)
printable = models.BooleanField(help_text='Is this image for publishing aims?')
restricted = models.BooleanField(help_text='Is this image only for selected people?')
image = models.ImageField('Image file in hi resolution', upload_to="photos", height_field='height', width_field='width', core=True, help_text='Use the highest resolution possible.')
height = models.IntegerField(default=None, null=True, blank=True, help_text = "Image height in pixels (automatically filled in for you)")
width = models.IntegerField(default=None, null=True, blank=True, help_text = "Image width in pixels (automatically filled in for you)")

def __str__ (self):
return self.normal_image + ': ' + self.description

class Admin:
list_filter = ['normal_image']
search_fields = ['description', 'normal_image']
date_hierarchy = 'pub_date'
list_display = ('normal_image', 'description', 'pub_date')

class Meta:
verbose_name_plural = 'photos'
Save the file and run these commands:
$ python manage.py syncdb
Django will create for you tables and permissions.

Then run:
$ python manage.py runserver
and access to the administration panel to add your photos!

All photos will be stored in your media/photos/ directory. Files with the same name will be renamed automatically.

Note that there is the #1537 bug: "ImageField height_field and width_field does not update after changing the image"

0 commenti: