persa
persa

Reputation: 1

How to check if URL is in Model/DB already on a URL Shortener? Django

i've been learning Django for these past days and i'm trying to develop an url shortener. It's functional and works great but it misses something: Check if the URL already exists so it can return the short URL stored in db. At this moments it's just checks if the short url is unique and does not exist already, so it always create a new and unique short url for the same URL.

I've tried to use queryset's exists() in if ShortenerForm.objects.filter(url = cleaned_info['url']).exists(): but it always gave me an error object has no attribute 'cleaned_data'

How can i do that?

These are my files:

views.py

from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from utils.shorty.form import ShortenerForm

from shorty.models import Shortener


# Create your views here.
def home(request):
    template = "shorty/pages/index.html"

    context = {}

    context["form"] = ShortenerForm()

    if request.method == "GET":
        return render(request, template, context)

    elif request.method == "POST":
        used_form = ShortenerForm(request.POST)

        if used_form.is_valid():
            shortened_object = used_form.save()

            new_url = request.build_absolute_uri("/") + shortened_object.shortcode

            long_url = shortened_object.url

            context["new_url"] = new_url
            context["long_url"] = long_url

            return render(request, template, context)

        context["errors"] = used_form.errors

        return render(request, "shorty/pages/index.html")


def redirect_url_view(request, shortened_path):

    try:
        shortener = Shortener.objects.get(shortcode=shortened_path)

        shortener.redirectCount += 1

        shortener.save()

        return HttpResponseRedirect(shortener.url)

    except:
        raise Http404("Sorry this link does not exist")

form.py

from django import forms

from shorty.models import Shortener


class ShortenerForm(forms.ModelForm):

    url = forms.URLField(
        widget=forms.URLInput(
            attrs={"class": "form-control", "placeholder": "Enter URL"}
        )
    )

    class Meta:
        model = Shortener

        fields = ("url",)

models.py

from django.db import models
from utils.shorty.factory import create_short_url


# Create your models here.
class Shortener(models.Model):
    startDate = models.DateTimeField(auto_now_add=True)
    lastSeenDate = models.DateTimeField(auto_now=True)
    redirectCount = models.PositiveIntegerField(default=0)
    url = models.URLField()
    shortcode = models.CharField(max_length=6, unique=True, blank=True)

    class Meta:
        ordering = ["-startDate"]

    def __str__(self):
        return f"{self.url} to {self.shortcode}"

    def save(self, *args, **kwargs):

        if not self.shortcode:
            self.shortcode = create_short_url(self)

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

Thanks for your patience and time.

Upvotes: 0

Views: 111

Answers (0)

Related Questions