summaryrefslogtreecommitdiff
path: root/lib/upload/models.py
blob: ae2dab45c885b6d8dd2067e9f6388a8aa0d918bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import datetime
from django.db import models
from django.conf import settings
from django.template.defaultfilters import slugify
import mimetypes

class FileUpload(models.Model):
    upload_date = models.DateTimeField(auto_now_add=True)
    upload = models.FileField(upload_to="images/%s" %(datetime.datetime.today().strftime("%Y")))
    title = models.CharField(max_length=100)
    description = models.CharField(blank=True, max_length=200)
    content_type = models.CharField(editable=False, max_length=100)
    sub_type = models.CharField(editable=False, max_length=100)

    
    
    class Meta:
        ordering = ['upload_date', 'title']

    def __unicode__(self):
        return self.title
    
    def mime_type(self):
        return '%s/%s' % (self.content_type, self.sub_type)
    
    def type_slug(self):
        return slugify(self.sub_type)
    
    def is_image(self):
        if self.content_type == 'image':
            return True
        else:
            return False
    
    def get_absolute_url(self):
        return '%s%s' % (settings.IMAGES_URL, self.upload.url[33:])

    def save(self, *args, **kwargs):
        file_path = '%s%s' % (settings.MEDIA_ROOT, self.upload)
        (mime_type, encoding) = mimetypes.guess_type(file_path)
        try:
            [self.content_type, self.sub_type] = mime_type.split('/')
        except:
            self.content_type = 'text'
            self.sub_type = 'plain'
        super(FileUpload, self).save(*args, **kwargs)