Django appending /None to url

i am creating a logic for users to save posts as favourite, i finished creating but when i header over to the url http://127.0.0.1:8000/design/ui-ux/learn-ui-the-easy-way/save/ it automatically refreshes it self and now appends None to the url like this http://127.0.0.1:8000/design/ui-ux/learn-ui-the-easy-way/save/None and that is not what i am expecting.

views.py

@login_required
def designtut_favourite(request, designcat_slug, design_slug):
    user = request.user
    designtut = DesignTutorial.objects.get(slug=design_slug)

    profile = Profile.objects.get(user=user)

    if profile.favourite_design.filter(slug=design_slug).exists():
        profile.favourite_design.remove(designtut)
    else:
        profile.favourite_design.add(designtut)

    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    favourite_design = models.ManyToManyField(DesignTutorial)

urls.py

path('design/<designcat_slug>/<design_slug>/save/', views.designtut_favourite, name="design-save"),

template.html

<a href="{% url 'base:design-save' designtut.designcat.slug designtut.slug %}"><i class="fas fa-heart" "></i><span>Save</span></a>

views.py

from urllib.parse import urlparse
# import ALLOWED_HOSTS from your settings.py here!


@login_required
def designtut_favourite(request, designcat_slug, design_slug):
    user = request.user
    designtut = DesignTutorial.objects.get(slug=design_slug)

    profile = Profile.objects.get(user=user)

    if profile.favourite_design.filter(slug=design_slug).exists():
        profile.favourite_design.remove(designtut)
    else:
        profile.favourite_design.add(designtut)

    net_location = urlparse(request.META.get('HTTP_REFERER')).netloc
    for allowed_host in ALLOWED_HOSTS:
        if net_location in allowed_host:
            return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
    return HttpResponseRedirect("/")

It is important to note, that blindly redirecting to a site given in the request poses a potential security risk. Therefor I tried including a check with the ALLOWED_HOSTS. This should redirect to the landing page, if there is a None value in it, but also if somebody is lured into a phishing site.

Back to Top