models.py 1.81 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
24
25
26
27

    def __unicode__(self):
        return '<URL: %s>' % self.short

    class Meta:
        ordering = ['short']
28

29
30
31
    def get_absolute_url(self):
        return "%s/%s" % (settings.SERVERURL, self.short)

32
33
34
35
36
37
38
39
40
41
42
43
44
45
    @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
46

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

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

59
60
61
62
    full_name = models.CharField(
        blank = False,
        max_length = 100,
    )
Jean Michel Rouly's avatar
Jean Michel Rouly committed
63

64
    description = models.TextField( blank=True )
65
66

    def __unicode__(self):
67
        return '<Registered User: %s>' % self.username
68