1 from django.db import models
2 import catalogue.models
3 from django.db.models import permalink
4 from sorl.thumbnail import ImageField
5 from django.conf import settings
6 from django.core.files.storage import FileSystemStorage
7 from django.utils.datastructures import SortedDict
8 from django.template.loader import render_to_string
9 from django.core.cache import cache
10 from catalogue.utils import split_tags
11 from django.utils.safestring import mark_safe
12 from librarian import dcparser, picture
13 from slughifi import slughifi
15 from django.utils.translation import ugettext_lazy as _
16 from newtagging import managers
20 picture_storage = FileSystemStorage(location=path.join(settings.MEDIA_ROOT, 'pictures'), base_url=settings.MEDIA_URL + "pictures/")
23 class Picture(models.Model):
28 title = models.CharField(_('title'), max_length=120)
29 slug = models.SlugField(_('slug'), max_length=120, db_index=True, unique=True)
30 sort_key = models.CharField(_('sort key'), max_length=120, db_index=True, editable=False)
31 created_at = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True)
32 changed_at = models.DateTimeField(_('creation date'), auto_now=True, db_index=True)
33 xml_file = models.FileField('xml_file', upload_to="xml", storage=picture_storage)
34 image_file = ImageField(_('image_file'), upload_to="images", storage=picture_storage)
35 objects = models.Manager()
36 tagged = managers.ModelTaggedItemManager(catalogue.models.Tag)
37 tags = managers.TagDescriptor(catalogue.models.Tag)
39 class AlreadyExists(Exception):
43 ordering = ('sort_key',)
45 verbose_name = _('picture')
46 verbose_name_plural = _('pictures')
48 URLID_RE = r'[a-z0-9-]+'
49 FILEID_RE = r'[a-z0-9-]+'
51 def save(self, force_insert=False, force_update=False, reset_short_html=True, **kwargs):
52 from sortify import sortify
54 self.sort_key = sortify(self.title)
56 ret = super(Picture, self).save(force_insert, force_update)
59 self.reset_short_html()
63 def __unicode__(self):
67 def get_absolute_url(self):
68 return ('picture.views.picture_detail', [self.urlid()])
74 def from_xml_file(cls, xml_file, image_file=None, overwrite=False):
76 Import xml and it's accompanying image file.
78 from sortify import sortify
79 from django.core.files import File
80 from librarian.picture import WLPicture
81 close_xml_file = False
83 if not isinstance(xml_file, File):
84 xml_file = File(open(xml_file))
87 # use librarian to parse meta-data
88 picture_xml = WLPicture.from_file(xml_file)
90 pict, created = Picture.objects.get_or_create(slug=picture_xml.slug)
91 if not created and not overwrite:
92 raise Picture.AlreadyExists('Picture %s already exists' % picture_xml.slug)
94 pict.title = picture_xml.picture_info.title
96 # from nose.tools import set_trace; set_trace()
98 for part in picture_xml.partiter():
99 for motif in part['themes']:
100 tag, created = catalogue.models.Tag.objects.get_or_create(slug=slughifi(motif), category='theme')
103 tag.sort_key = sortify(tag.name)
107 pict.tags = catalogue.models.Tag.tags_from_info(picture_xml.picture_info) + \
110 if image_file is not None:
113 img = picture_xml.image_file()
115 pict.image_file.save(path.basename(picture_xml.image_path), File(img))
117 pict.xml_file.save("%s.xml" % pict.slug, File(xml_file))
125 def picture_list(cls, filter=None):
126 """Generates a hierarchical listing of all pictures
127 Pictures are optionally filtered with a test function.
130 pics = cls.objects.all().order_by('sort_key')\
131 .only('title', 'slug', 'image_file')
134 pics = pics.filter(filter).distinct()
136 pics_by_author = SortedDict()
138 for tag in catalogue.models.Tag.objects.filter(category='author'):
139 pics_by_author[tag] = []
142 authors = list(pic.tags.filter(category='author'))
144 for author in authors:
145 pics_by_author[author].append(pic)
149 return pics_by_author, orphans
153 if not hasattr(self, '_info'):
154 info = dcparser.parse(self.xml_file.path, picture.PictureInfo)
158 def reset_short_html(self):
162 cache_key = "Picture.short_html/%d" % (self.id)
163 cache.delete(cache_key)
165 def short_html(self):
167 cache_key = "Picture.short_html/%d" % (self.id)
168 short_html = cache.get(cache_key)
172 if short_html is not None:
173 return mark_safe(short_html)
175 tags = self.tags.filter(category__in=('author', 'kind', 'epoch'))
176 tags = split_tags(tags)
178 short_html = unicode(render_to_string('picture/picture_short.html',
179 {'picture': self, 'tags': tags}))
182 cache.set(cache_key, short_html, catalogue.models.CACHE_FOREVER)
183 return mark_safe(short_html)