models.py 1.69 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
5
import random, string

Jean Michel Rouly's avatar
Jean Michel Rouly committed
6

Jean Michel Rouly's avatar
Jean Michel Rouly committed
7
class URL( models.Model ):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
8
9
10
11
12
13
    """
    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
14
    owner = models.ForeignKey( User )
Jean Michel Rouly's avatar
Jean Michel Rouly committed
15
16
    date_created = models.DateTimeField( default=timezone.now() )

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

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

    class Meta:
        ordering = ['short']
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

    @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
42

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

49
50
51
52
53
    username = models.CharField(
        blank = False,
        max_length = 30,
        primary_key = True
    )
Jean Michel Rouly's avatar
Jean Michel Rouly committed
54

55
56
57
58
    full_name = models.CharField(
        blank = False,
        max_length = 100,
    )
Jean Michel Rouly's avatar
Jean Michel Rouly committed
59

60
    description = models.TextField( blank=True )
61
62

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