added code to generate and redirect a shorturl
parent
5332a180a1
commit
6da57fbe06
|
|
@ -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"]
|
||||
|
|
|
|||
|
|
@ -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"]
|
||||
|
|
|
|||
|
|
@ -0,0 +1,9 @@
|
|||
from django.urls import path
|
||||
|
||||
from . import views
|
||||
|
||||
app_name = "shorturls"
|
||||
|
||||
urlpatterns = [
|
||||
path("<str:shorturl>/", views.ShorturlsRedirectView.as_view(), name="redirect"),
|
||||
]
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
|
|||
Loading…
Reference in New Issue