diff --git a/shorturls/admin.py b/shorturls/admin.py index 8c38f3f..094ea45 100644 --- a/shorturls/admin.py +++ b/shorturls/admin.py @@ -1,3 +1,8 @@ from django.contrib import admin -# Register your models here. +from .models import ShortURL + + +@admin.register(ShortURL) +class ShortURLAdmin(admin.ModelAdmin): + list_display = ["long_url", "short_url", "followed"] diff --git a/shorturls/models.py b/shorturls/models.py index 71a8362..e9cdc4a 100644 --- a/shorturls/models.py +++ b/shorturls/models.py @@ -1,3 +1,18 @@ from django.db import models -# Create your models here. +from .utils import create_short_url + + +class ShortURL(models.Model): + created = models.DateTimeField(auto_now_add=True) + followed = models.PositiveIntegerField(default=0) + long_url = models.TextField() + short_url = models.CharField(max_length=20, unique=True, blank=True) + + def save(self, *args, **kwargs): + if not self.short_url: + self.short_url = create_short_url(self) + super().save() + + class Meta: + ordering = ["created"] diff --git a/shorturls/urls.py b/shorturls/urls.py new file mode 100644 index 0000000..c60903e --- /dev/null +++ b/shorturls/urls.py @@ -0,0 +1,9 @@ +from django.urls import path + +from . import views + +app_name = "shorturls" + +urlpatterns = [ + path("/", views.ShorturlsRedirectView.as_view(), name="redirect"), +] diff --git a/shorturls/utils.py b/shorturls/utils.py new file mode 100644 index 0000000..6e6fe21 --- /dev/null +++ b/shorturls/utils.py @@ -0,0 +1,19 @@ +from random import choice +from string import ascii_letters, digits + +from django.conf import settings + +SIZE = getattr(settings, "MAXIMUM_URL_CHARS", 10) +AVAILABLE_CHARS = ascii_letters + digits + + +def create_random_code(chars=AVAILABLE_CHARS): + return "".join([choice(chars) for _ in range(SIZE)]) + + +def create_short_url(model_instance): + random_code = create_random_code() + model_class = model_instance.__class__ + if model_class.objects.filter(short_url=random_code).exists(): + return create_short_url(model_instance) + return random_code diff --git a/shorturls/views.py b/shorturls/views.py index 91ea44a..8341564 100644 --- a/shorturls/views.py +++ b/shorturls/views.py @@ -1,3 +1,12 @@ -from django.shortcuts import render +from django.shortcuts import get_object_or_404 +from django.views.generic.base import RedirectView -# Create your views here. +from .models import ShortURL + + +class ShorturlsRedirectView(RedirectView): + def get_redirect_url(self, *args, **kwargs): + url = get_object_or_404(ShortURL, short_url=kwargs["shorturl"]) + url.followed += 1 + url.save() + return url.long_url