dvd-collection / collection / models.py

from django.db import models
from django.utils.text import slugify
from collection.managers import MovieManager
import datetime
import urllib2
from django.core.files.uploadedfile import SimpleUploadedFile
import sys
from django.core.mail import mail_admins
from django.contrib.auth.models import User

def get_length(value):
    tokens = value.split(' ')
    if tokens[1] == 'h':
        hours = int(tokens[0])
    else:
        hours = 0
        mins = int(tokens[0])
        return datetime.datetime(1983, 05, 10, hours, mins)
    try:
        mins = int(tokens[2])
    except IndexError:
        mins = 0
    return datetime.datetime(1983, 05, 10, hours, mins)

class Genre(models.Model):
    name = models.CharField(max_length=20, unique=True, help_text='The name of this genre.')
    slug = models.SlugField(help_text='Used to form the URL to this genre.')
    def __unicode__(self):
        return u"%s" % self.name
    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        return super(Genre, self).save(*args, **kwargs)
    @models.permalink
    def get_absolute_url(self):
        return ('browse_genre', [self.slug])

class Director(models.Model):
    name = models.CharField(max_length=40, unique=True)
    slug = models.SlugField()
    def __unicode__(self):
        return u"%s" % self.name
    class Meta:
        ordering = ['name']
    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        return super(Director, self).save(*args, **kwargs)
    @models.permalink
    def get_absolute_url(self):
        return ('browse_director', [self.slug])

class Movie(models.Model):
    FORMAT_CHOICES = (
        (10, 'VHS'),
        (20, 'DVD'),
        (30, 'HD-DVD'),
        (40, 'Blu-Ray'),
        (50, '3D Blu-Ray'),
        (90, 'Torrent'),
    )
    title = models.CharField(max_length=80, help_text='What is the title of this movie?')
    slug = models.SlugField(help_text='Used to form the URL to this movie.')
    added_on = models.DateField(auto_now_add=True)
    format = models.PositiveSmallIntegerField(choices=FORMAT_CHOICES, help_text='What format is this movie in?')
    genre = models.ForeignKey(Genre, help_text='Which genre is this movie?')
    rating = models.PositiveSmallIntegerField(blank=True, null=True, help_text='Do you currently have a rating for this title? 0-10')
    watched = models.PositiveIntegerField(default=0, help_text='How many times have you watched this film?')
    last_watched = models.DateField(blank=True, null=True)
    purchase_price = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True, help_text='What was the purchase price?')
    market_price = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True, help_text='Do you happen to know the market price?')
    imdb = models.CharField(max_length=20,blank=True, null=True, help_text='You can place the IMDb title ID number here.')
    youtube = models.CharField(max_length=30, blank=True, null=True, help_text='You can place a link to a trailer on YouTube here.')
    poster = models.URLField(blank=True, null=True)
    poster_img = models.ImageField(upload_to='posters', blank=True, null=True)
    year = models.PositiveSmallIntegerField(blank=True, null=True, help_text='This is used when obtaining the data from IMDb.')
    released = models.DateField(blank=True, null=True)
    length = models.DateTimeField(blank=True, null=True)
    director = models.ForeignKey(Director, blank=True, null=True)
    plot = models.TextField(blank=True)
    imdb_rating = models.PositiveSmallIntegerField(blank=True, null=True)
    objects = MovieManager()
    def __unicode__(self):
        return u"%s" % self.title
    class Meta:
        ordering = ['title']
    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        return super(Movie, self).save(*args, **kwargs)
    @models.permalink
    def get_absolute_url(self):
        return ('movie_detail', [self.slug])
    def get_poster(self):
        req = urllib2.Request(self.poster)
        req.add_header('Referer', 'http://www.imdb.com/title/%s/' % self.imdb)
        req.add_header('User-agent', 'Mozilla/5.0 (X11; Linux x86_64; rv:20.0) Gecko/20100101 Firefox/20.0')
        return urllib2.urlopen(req).read()
    def import_imdb(self, omdb):
        try:
            if omdb['Response'] == 'True':
                self.imdb = omdb['imdbID']
                self.poster = omdb['Poster'] if omdb['Poster'] != 'N/A' else None
                self.year = int(omdb['Year'])
                self.released = datetime.datetime.strptime(omdb['Released'], "%d %b %Y") if omdb['Released'] != 'N/A' else None
                self.length = get_length(omdb['Runtime']) if omdb['Runtime'] != 'N/A' else None
                self.plot = omdb['Plot']
                self.imdb_rating = int(round(float(omdb['imdbRating']))) if omdb['imdbRating'] != 'N/A' else None
                director = Director.objects.get_or_create(name=omdb['Director'])[0]
                self.director = director
                self.save()
                if self.poster:
                    poster = self.get_poster()
                    self.poster_img.save("%s.jpg" % self.slug, SimpleUploadedFile("%s.jpg" % self.slug, poster, 'image/jpeg'))
                return True
            return False
        except:
            value = sys.exc_info()[1]
            mail_admins('IMDb exception thrown: %s' % self.get_absolute_url(), value.__repr__())
            return False

class Watchlist(models.Model):
    owner = models.OneToOneField(User)
    movies = models.ManyToManyField(Movie)
    genres = models.ManyToManyField(Genre)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.