Как проверить, есть ли URL в модели/БД уже на URL Shortener? Django

Я изучаю Django в последние дни и пытаюсь разработать укоротитель URL. Он функционален и работает отлично, но ему не хватает кое-чего: проверки, существует ли уже URL, чтобы он мог вернуть короткий URL, хранящийся в базе данных. В данный момент он просто проверяет, является ли короткий URL уникальным и не существует ли он уже, поэтому он всегда создает новый уникальный короткий URL для того же URL.

Я пытался использовать exists() queryset в if ShortenerForm.objects.filter(url = cleaned_info['url']).exists():, но он всегда выдавал ошибку object has no attribute 'cleaned_data'

Как я могу это сделать?

Вот мои файлы:

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)

Спасибо за ваше терпение и время.

Вернуться на верх