import datetime

from random import randint
from django.template.defaultfilters import slugify
from django.db import models
from django.utils import timezone

class Language(models.Model):
    name = models.CharField(max_length=50)
    description = models.TextField()
    documentation_url = models.URLField(max_length=200)

    def __str__(self):
        return self.name

class Service(models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField(max_length=110, blank=True, unique=True)
    pub_date = models.DateTimeField('date published')
    url = models.URLField(max_length=200)
    description = models.TextField()
    code_language = models.ForeignKey(Language)
    code_solution = models.TextField()

    #Then override models save method:
    def save(self, *args, **kwargs):
        if not self.id:
            #Only set the slug when the object is created.
            slugurl = slugify(self.name).lower() #Or whatever you want the slug to use
            if Service.objects.filter(slug=slugurl).exists():
                str_random = str(randint(0, 100))
                self.slug = slugurl + '_' + str_random
            else:
                self.slug = slugurl

        super(Service, self).save(*args, **kwargs)

    def __str__(self):
        return self.name

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=2)
