Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

python - 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')
question from:https://stackoverflow.com/questions/65866869/how-to-send-url-as-slug-field-into-url-in-django

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'),
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...