models.py 2.04 KB
Newer Older
1
from django.db import models
Jean Michel Rouly's avatar
Jean Michel Rouly committed
2 3
from django.contrib.auth.models import User
from django.utils import timezone
4
from django.conf import settings
5 6
import random, string

Jean Michel Rouly's avatar
Jean Michel Rouly committed
7

Jean Michel Rouly's avatar
Jean Michel Rouly committed
8
class URL( models.Model ):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
9 10 11 12 13 14
    """
    This model represents a stored URL redirection rule. Each URL has an
    owner, target url, short identifier, click counter, and expiration
    date.
    """

Jean Michel Rouly's avatar
Jean Michel Rouly committed
15
    owner = models.ForeignKey( User )
Jean Michel Rouly's avatar
Jean Michel Rouly committed
16 17
    date_created = models.DateTimeField( default=timezone.now() )

Jean Michel Rouly's avatar
Jean Michel Rouly committed
18
    target = models.URLField( max_length = 1000 )
19
    short = models.CharField( primary_key = True, max_length = 20 )
Jean Michel Rouly's avatar
Jean Michel Rouly committed
20
    clicks = models.IntegerField( default = 0 )
21
    expires = models.DateTimeField( blank = True, null = True )
22 23

    def __unicode__(self):
24
        return '<%s : %s>' % (self.owner.username, self.target)
25 26 27

    class Meta:
        ordering = ['short']
28

29
    def get_absolute_url(self):
30 31 32 33
        from django.contrib.sites.models import Site
        current_site = Site.objects.get_current()
        site_url = current_site.domain
        return "%s/%s" % (site_url, self.short)
34

35 36 37 38 39 40 41 42 43 44 45 46 47 48
    @staticmethod
    def generate_valid_short():
        selection = string.ascii_lowercase + string.digits
        tries = 0
        while True:
            short = ''.join(random.choice(selection) for i in range(5))
            try:
                urls = URL.objects.get( short__iexact = short )
                tries += 1
            except URL.DoesNotExist:
                return short
            if tries > 100:
                return None

Jean Michel Rouly's avatar
Jean Michel Rouly committed
49

50
class RegisteredUser( models.Model ):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
51 52 53 54 55
    """
    This is simply a wrapper model which, if an object exists, indicates
    that that user is registered.
    """

56 57 58 59 60
    username = models.CharField(
        blank = False,
        max_length = 30,
        primary_key = True
    )
Jean Michel Rouly's avatar
Jean Michel Rouly committed
61

62 63 64 65
    full_name = models.CharField(
        blank = False,
        max_length = 100,
    )
Jean Michel Rouly's avatar
Jean Michel Rouly committed
66

67
    description = models.TextField( blank=True )
68

69 70
    approved = models.BooleanField()

71
    def __unicode__(self):
72
        return '<Registered User: %s - Approval Status: %s>' % (self.username, self.approved)
73