1
from django.db import models
2
from django.contrib.contenttypes.models import ContentType
3
from django.contrib.contenttypes import generic
4
from django.contrib.auth.models import User
5
from django.utils.translation import ugettext_lazy as _
6
from django.db import IntegrityError
7
from datetime import datetime
9
from settings import MEDIA_ROOT
12
from widelands.wiki.models import Article
14
class ImageManager(models.Manager):
16
We overwrite the defaults manager to make sure
17
that the create function checks for validity. We also include
18
some convenience functions here
20
def has_image(self,image_name):
21
return bool(self.filter(name=image_name).count())
24
def create(self,**keyw):
26
Makes sure that no image/revision pair is already in the database
28
if "name" not in keyw or "revision" not in keyw:
29
raise IntegrityError("needs name and revision as keywords")
31
if self.filter(name=keyw["name"],revision=keyw["revision"]).count():
32
raise Image.AlreadyExisting()
34
return super(ImageManager,self).create(**keyw)
36
def create_and_save_image(self,user,image):
37
# if self.has_image(name):
38
# raise RuntimeError,"Image with name %s already exists. This is likely an Error" % name
39
name = image.name.lower()
40
im = self.create(content_type=ContentType.objects.get_for_model(Article), object_id=1,
41
user=user,revision=1,name=name)
43
# Image.objects.create(name=name,content_type=ContentType.objects.get_for_model(Article),
44
# image="/images/%s" % name)
45
path = "%s/images/%s" % (MEDIA_ROOT,image.name)
48
destination = open(path,"wb")
49
for chunk in image.chunks():
50
destination.write(chunk)
57
class Image(models.Model):
58
class AlreadyExisting(IntegrityError):
60
return "The combination of image/revision is already in the database"
65
# Generic Foreign Key Fields
66
content_type = models.ForeignKey(ContentType)
67
object_id = models.PositiveIntegerField(_('object ID'))
68
content_object = generic.GenericForeignKey()
70
name = models.CharField(max_length="100")
71
revision = models.PositiveIntegerField()
74
user = models.ForeignKey(User)
75
ip_address = models.IPAddressField(_('IP address'), null=True, blank=True)
78
date_submitted = models.DateTimeField(_('date/time submitted'), default = datetime.now)
79
image = models.ImageField(upload_to="images/")
81
objects = ImageManager()
83
def __unicode__(self):
86
def get_content_object(self):
88
taken from threadedcomments:
90
Wrapper around the GenericForeignKey due to compatibility reasons
91
and due to ``list_display`` limitations.
93
return self.content_object
96
ordering = ('-date_submitted',)
97
verbose_name = _("Image")
98
verbose_name_plural = _("Images")
99
get_latest_by = "date_submitted"