models.py 1.28 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
6
import random, string

7
# Create your models here.
Jean Michel Rouly's avatar
Jean Michel Rouly committed
8
class URL( models.Model ):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
9
    owner = models.ForeignKey( User )
Jean Michel Rouly's avatar
Jean Michel Rouly committed
10
11
    date_created = models.DateTimeField( default=timezone.now() )

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

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

    class Meta:
        ordering = ['short']
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

    @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

37
38
class RegisteredUser( models.Model ):
    user = models.ForeignKey( User, primary_key = True )
39
    description = models.TextField()
40
41
42
43

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