Reputation: 2096
I'm new to Django. I'm now creating a project. In that project, I've links like this:
https://localhost:8000/example.com/example/path/
In the URL the example.com/example/path/
can be dynamically long as like this
example.com
or
example.com/asset/css/style.css
or
domain.com/core/content/auth/assets/js/vendor/jquery.js
I've used <str:domainurl>
But is not working. As it has multiple forward slashes. And the forward slashes URL length generated while web scraping.
So is there is a way to use the full URL as one variable?
Upvotes: 1
Views: 1053
Reputation: 111
try this
urls.py
from django.urls import path
from app.views import extract_path
urlpatterns = [
path('<path:url>', extract_path, name='extract_path'),
]
views.py
from django.http import JsonResponse
def extract_path(request, url):
full_path = request.get_full_path()
extracted_path = full_path.lstrip('/')
# You can use either url or extracted_path
# as they both return the same value.
return JsonResponse({'extracted_path': extracted_path, 'url': url})
and response:
{
"extracted_path": "example.com/example/path/",
"url": "example.com/example/path/"
}
Upvotes: 1
Reputation: 21787
You want to be using the path
path converter [Django docs]:
path('<path:domainurl>/', some_view)
Quoting Django docs:
path - Matches any non-empty string, including the path separator, '/'. This allows you to match against a complete URL path rather than a segment of a URL path as with str.
Note: Design your url patterns and order them carefully if you are going to use this. Django uses the first matching url pattern to serve any request.
Upvotes: 3
Reputation: 421
If you want Django to match some custom strings take a look at re_path
(https://docs.djangoproject.com/en/3.1/ref/urls/#django.urls.re_path) function. It basically allows you to pass a regular expression.
For the urls samples you provided you would probably want an expression like this (in your urls.py
):
re_path(r'^(?P<my_url>[a-z0-9/\.]+)$', your_view_function)
This will pass a my_url
kwarg to your view which you can then process as you want.
Upvotes: 0