1

How to send url as slug field into url in Django

I have my urls.py as this:

from django.urls import path
from . import views
urlpatterns = [
    path('link',views.get_text,name='text'),
    path('link/<link>',views.show,name='show')
]

When I enter a url like http://127.0.0.1:8000/link/https://www.geeksforgeeks.org/gate-cs-notes-gq/, it is showing page not found as it is checking the / in the slug url. I am storing the url and other fields in database, so I want to retrieve the database objects using the url. How to do such that when I enter a url in the browser, it takes the entire url as link field in urls.py , so that I can retrieve the db objects from views.py in this way:

def show(request,link):
    objs = Links.objects.filter(link=link).values()
    return HttpResponse('link')

Submitted January 24th 2021 by Admin

Answers
0

Pass the URL in the querystring of the requesting URL: http://127.0.0.1:8000/link/?link=https://www.geeksforgeeks.org/gate-cs-notes-gq/

The data from the querystring is available in the request.GET dictionary in your view

def link_view(request): if 'link' in request.GET: objs = Links.objects.filter(link=request.GET['link']).values() return HttpResponse(...) else: # Handle no link provided (views.get_text)

Your url patterns then only need to define one path that handles both cases where a URL is provided or not

urlpatterns = [ path('link/', views.link_view, name='link_view'),
]

Admin | 8 months ago



Relevant Questions