Davide Muzzarelli

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

published on 18.07.2006 in # in english, * livello avanzato, django, python

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”

Dicci Cosa Pensi

Lascia un commento qui sotto...

Confermando l'invio accetti di aver letto le note legali e di aderire ad esse.