I'm working on a Django(2) project in which I need to pass an URL as a parameter in a Django URL,
Here's what i have tried:
urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^api/(?P<address>.*)/$', PerformImgSegmentation.as_view()),
]
views.py:
class PerformImgSegmentation(generics.ListAPIView):
def get(self, request, *args, **kwargs):
img_url = self.kwargs.get('address')
print(img_url)
print('get request')
return 'Done'
But it doesn't work, I have passed an argument with the name as address via postman, but it failed.
It returns this error:
Not Found: /api/
[05/Sep/2018 15:28:06] "GET /api/ HTTP/1.1" 404 2085
Django 2.0 and later use now path func constructors to specify URLs. I'm not sure if there's still backwards compatibility; you can try that with a simple example. However if you are starting to write an app you should use path:
path('api/<str:encoded_url>/', view_action)
To avoid confusion with a stantard path to view in your app, I do not recommend using the path converter instead of the str (the former lets you match /, while the other does not).
You can get more help for transitioning from url to path with this article.
Second step, get the encoded_url as an argument in the view. You need to decode it: to pass a url inside the get url, you use ASCII encoding that substitutes certain reserved characters for others (for example, the forward slash).
You can encode and decode urls easily with urllib (there are other modules as well). For Python 3.7 syntax is as follows (docs here)
>>> urllib.parse.quote("http://www.google.com")
'http%3A//www.google.com'
>>> urllib.parse.unquote('http%3A//www.google.com')
'http://www.google.com'
Remember: if you pass the url without quoting it won't match: you are not accepting matches for slashes with that path expression. (Edit: quote method default does not convert forward slashes, for that you need to pass: quote(<str>, safe='')
So for example your GET call should look: /api/http%3A%2F%2Fwww.google.com. However it's better if you pass the URL as a get parameter and in the paths you only care aboubt readability (for example /api/name_to_my_method?url=http%3A%2F%2Fwww.google.com). Path engineering is important for readability and passing a quoted URL through is usually not ebst practice (though perfectly possible).
Django 2.0 is providing the Path Converters to convert the path parameters into appropriate types, which also includes a converter for urls, take a look at the docs.
So, your URLs can be like this:
path('api/<path:encoded_url>/', PerformImgSegmentation.as_view()),
So, the path converter will Matches any non-empty string, including the path separator, '/'. This allows you to match against a complete URL path rather than just a segment of a URL path as with str.
Then in the view, we can simply get our URL values from kwargs like this:
img_url = self.kwargs.get('encoded_url')
print(img_url)
Are you trying to pass the url https://i.imgur.com/TGJHFe1.jpg as a parameter from the django template to the view ?
You could simple write in your app's url.py:
path(api/<path:the_url_you_want_to_pass>', PerformImgSegmentation.as_view())
Please have a look at this article.
Related
I have some code and when it executes, it throws a NoReverseMatch, saying:
NoReverseMatch at /my_url/ Reverse for 'my_url_name' with arguments '()' and keyword arguments '{}' not found. n pattern(s) tried: []
What does this mean, and what can I do about it?
The NoReverseMatch error is saying that Django cannot find a matching url pattern for the url you've provided in any of your installed app's urls.
The NoReverseMatch exception is raised by django.core.urlresolvers when a matching URL in your URLconf cannot be identified based on the parameters supplied.
To start debugging it, you need to start by disecting the error message given to you.
NoReverseMatch at /my_url/
This is the url that is currently being rendered, it is this url that your application is currently trying to access but it contains a url that cannot be matched
Reverse for 'my_url_name'
This is the name of the url that it cannot find
with arguments '()' and
These are the non-keyword arguments its providing to the url
keyword arguments '{}' not found.
These are the keyword arguments its providing to the url
n pattern(s) tried: []
These are the patterns that it was able to find in your urls.py files that it tried to match against
Start by locating the code in your source relevant to the url that is currently being rendered - the url, the view, and any templates involved. In most cases, this will be the part of the code you're currently developing.
Once you've done this, read through the code in the order that django would be following until you reach the line of code that is trying to construct a url for your my_url_name. Again, this is probably in a place you've recently changed.
Now that you've discovered where the error is occuring, use the other parts of the error message to work out the issue.
The url name
Are there any typos?
Have you provided the url you're trying to access the given name?
If you have set app_name in the app's urls.py (e.g. app_name = 'my_app') or if you included the app with a namespace (e.g. include('myapp.urls', namespace='myapp'), then you need to include the namespace when reversing, e.g. {% url 'myapp:my_url_name' %} or reverse('myapp:my_url_name').
Arguments and Keyword Arguments
The arguments and keyword arguments are used to match against any capture groups that are present within the given url which can be identified by the surrounding () brackets in the url pattern.
Assuming the url you're matching requires additional arguments, take a look in the error message and first take a look if the value for the given arguments look to be correct.
If they aren't correct:
The value is missing or an empty string
This generally means that the value you're passing in doesn't contain the value you expect it to be. Take a look where you assign the value for it, set breakpoints, and you'll need to figure out why this value doesn't get passed through correctly.
The keyword argument has a typo
Correct this either in the url pattern, or in the url you're constructing.
If they are correct:
Debug the regex
You can use a website such as regexr to quickly test whether your pattern matches the url you think you're creating, Copy the url pattern into the regex field at the top, and then use the text area to include any urls that you think it should match against.
Common Mistakes:
Matching against the . wild card character or any other regex characters
Remember to escape the specific characters with a \ prefix
Only matching against lower/upper case characters
Try using either a-Z or \w instead of a-z or A-Z
Check that pattern you're matching is included within the patterns tried
If it isn't here then its possible that you have forgotten to include your app within the INSTALLED_APPS setting (or the ordering of the apps within INSTALLED_APPS may need looking at)
Django Version
In Django 1.10, the ability to reverse a url by its python path was removed. The named path should be used instead.
If you're still unable to track down the problem, then feel free to ask a new question that includes what you've tried, what you've researched (You can link to this question), and then include the relevant code to the issue - the url that you're matching, any relevant url patterns, the part of the error message that shows what django tried to match, and possibly the INSTALLED_APPS setting if applicable.
A very common error is when you get with arguments ('',). This is caused by something like this:
{% url 'view-name' does_not_exist %}
As does_not_exist doesn't exist, django evaluates it to the empty string, causing this error message.
If you install django-fastdev you will instead get a nice crash saying does_not_exist doesn't exist which is the real problem.
With django-extensions you can make sure your route in the list of routes:
./manage.py show_urls | grep path_or_name
If the route is missing you probably have not imported the application.
It may be that it's not loading the template you expect. I added a new class that inherited from UpdateView - I thought it would automatically pick the template from what I named my class, but it actually loaded it based on the model property on the class, which resulted in another (wrong) template being loaded. Once I explicitly set template_name for the new class, it worked fine.
The arguments part is typically an object from your models. Remember to add it to your context in the view. Otherwise a reference to the object in the template will be empty and therefore not match a url with an object_id.
Watch out for different arguments passing between reverse() and redirect() for example:
url(r"^some_app/(?P<some_id>\d+)/$", some_view_function, name="some_view")
will work with:
reverse("some_view", kwargs={"some_id": my_id})
and:
redirect("some_view", some_id=my_id)
but not with:
reverse("some_view", some_id=my_id)
and:
redirect("some_view", kwargs={"some_id": my_id})
In my urls.py I have:
urlpatterns = [
url(r'^admin/', admin.site.urls, name='admin'),
url(r'^django-admin/', RedirectView.as_view(url='/admin/', permanent=True)),
]
So if I go to localhost:8000/django-admin/ it successfully redirects me to localhost:8000/admin/, and if I go to localhost:8000/django-admin/my-app/ it also redirects me to localhost:8000/admin/.
How could I make localhost:8000/django-admin/my-app/ go to localhost:8000/admin/my-app/? And the same for every possible subpath e.g. localhost:8000/django-admin/my-app/my-view, localhost:8000/django-admin/another-app/, etc?
According to the docs something like this should work, you can capture groups from the path and pass them to the url
The given URL may contain dictionary-style string formatting, which will be interpolated against the parameters captured in the URL. Because keyword interpolation is always done (even if no arguments are passed in), any "%" characters in the URL must be written as "%%" so that Python will convert them to a single percent sign on output.
url(r'^django-admin/(?P<rest>.*)', RedirectView.as_view(url='/admin/%(rest)s', permanent=True)
This website is particularly useful for figuring out how the built-in class-based views work http://ccbv.co.uk/projects/Django/2.2/django.views.generic.base/RedirectView/#get_redirect_url
I have some code and when it executes, it throws a NoReverseMatch, saying:
NoReverseMatch at /my_url/ Reverse for 'my_url_name' with arguments '()' and keyword arguments '{}' not found. n pattern(s) tried: []
What does this mean, and what can I do about it?
The NoReverseMatch error is saying that Django cannot find a matching url pattern for the url you've provided in any of your installed app's urls.
The NoReverseMatch exception is raised by django.core.urlresolvers when a matching URL in your URLconf cannot be identified based on the parameters supplied.
To start debugging it, you need to start by disecting the error message given to you.
NoReverseMatch at /my_url/
This is the url that is currently being rendered, it is this url that your application is currently trying to access but it contains a url that cannot be matched
Reverse for 'my_url_name'
This is the name of the url that it cannot find
with arguments '()' and
These are the non-keyword arguments its providing to the url
keyword arguments '{}' not found.
These are the keyword arguments its providing to the url
n pattern(s) tried: []
These are the patterns that it was able to find in your urls.py files that it tried to match against
Start by locating the code in your source relevant to the url that is currently being rendered - the url, the view, and any templates involved. In most cases, this will be the part of the code you're currently developing.
Once you've done this, read through the code in the order that django would be following until you reach the line of code that is trying to construct a url for your my_url_name. Again, this is probably in a place you've recently changed.
Now that you've discovered where the error is occuring, use the other parts of the error message to work out the issue.
The url name
Are there any typos?
Have you provided the url you're trying to access the given name?
If you have set app_name in the app's urls.py (e.g. app_name = 'my_app') or if you included the app with a namespace (e.g. include('myapp.urls', namespace='myapp'), then you need to include the namespace when reversing, e.g. {% url 'myapp:my_url_name' %} or reverse('myapp:my_url_name').
Arguments and Keyword Arguments
The arguments and keyword arguments are used to match against any capture groups that are present within the given url which can be identified by the surrounding () brackets in the url pattern.
Assuming the url you're matching requires additional arguments, take a look in the error message and first take a look if the value for the given arguments look to be correct.
If they aren't correct:
The value is missing or an empty string
This generally means that the value you're passing in doesn't contain the value you expect it to be. Take a look where you assign the value for it, set breakpoints, and you'll need to figure out why this value doesn't get passed through correctly.
The keyword argument has a typo
Correct this either in the url pattern, or in the url you're constructing.
If they are correct:
Debug the regex
You can use a website such as regexr to quickly test whether your pattern matches the url you think you're creating, Copy the url pattern into the regex field at the top, and then use the text area to include any urls that you think it should match against.
Common Mistakes:
Matching against the . wild card character or any other regex characters
Remember to escape the specific characters with a \ prefix
Only matching against lower/upper case characters
Try using either a-Z or \w instead of a-z or A-Z
Check that pattern you're matching is included within the patterns tried
If it isn't here then its possible that you have forgotten to include your app within the INSTALLED_APPS setting (or the ordering of the apps within INSTALLED_APPS may need looking at)
Django Version
In Django 1.10, the ability to reverse a url by its python path was removed. The named path should be used instead.
If you're still unable to track down the problem, then feel free to ask a new question that includes what you've tried, what you've researched (You can link to this question), and then include the relevant code to the issue - the url that you're matching, any relevant url patterns, the part of the error message that shows what django tried to match, and possibly the INSTALLED_APPS setting if applicable.
A very common error is when you get with arguments ('',). This is caused by something like this:
{% url 'view-name' does_not_exist %}
As does_not_exist doesn't exist, django evaluates it to the empty string, causing this error message.
If you install django-fastdev you will instead get a nice crash saying does_not_exist doesn't exist which is the real problem.
With django-extensions you can make sure your route in the list of routes:
./manage.py show_urls | grep path_or_name
If the route is missing you probably have not imported the application.
It may be that it's not loading the template you expect. I added a new class that inherited from UpdateView - I thought it would automatically pick the template from what I named my class, but it actually loaded it based on the model property on the class, which resulted in another (wrong) template being loaded. Once I explicitly set template_name for the new class, it worked fine.
The arguments part is typically an object from your models. Remember to add it to your context in the view. Otherwise a reference to the object in the template will be empty and therefore not match a url with an object_id.
Watch out for different arguments passing between reverse() and redirect() for example:
url(r"^some_app/(?P<some_id>\d+)/$", some_view_function, name="some_view")
will work with:
reverse("some_view", kwargs={"some_id": my_id})
and:
redirect("some_view", some_id=my_id)
but not with:
reverse("some_view", some_id=my_id)
and:
redirect("some_view", kwargs={"some_id": my_id})
I have some code and when it executes, it throws a NoReverseMatch, saying:
NoReverseMatch at /my_url/ Reverse for 'my_url_name' with arguments '()' and keyword arguments '{}' not found. n pattern(s) tried: []
What does this mean, and what can I do about it?
The NoReverseMatch error is saying that Django cannot find a matching url pattern for the url you've provided in any of your installed app's urls.
The NoReverseMatch exception is raised by django.core.urlresolvers when a matching URL in your URLconf cannot be identified based on the parameters supplied.
To start debugging it, you need to start by disecting the error message given to you.
NoReverseMatch at /my_url/
This is the url that is currently being rendered, it is this url that your application is currently trying to access but it contains a url that cannot be matched
Reverse for 'my_url_name'
This is the name of the url that it cannot find
with arguments '()' and
These are the non-keyword arguments its providing to the url
keyword arguments '{}' not found.
These are the keyword arguments its providing to the url
n pattern(s) tried: []
These are the patterns that it was able to find in your urls.py files that it tried to match against
Start by locating the code in your source relevant to the url that is currently being rendered - the url, the view, and any templates involved. In most cases, this will be the part of the code you're currently developing.
Once you've done this, read through the code in the order that django would be following until you reach the line of code that is trying to construct a url for your my_url_name. Again, this is probably in a place you've recently changed.
Now that you've discovered where the error is occuring, use the other parts of the error message to work out the issue.
The url name
Are there any typos?
Have you provided the url you're trying to access the given name?
If you have set app_name in the app's urls.py (e.g. app_name = 'my_app') or if you included the app with a namespace (e.g. include('myapp.urls', namespace='myapp'), then you need to include the namespace when reversing, e.g. {% url 'myapp:my_url_name' %} or reverse('myapp:my_url_name').
Arguments and Keyword Arguments
The arguments and keyword arguments are used to match against any capture groups that are present within the given url which can be identified by the surrounding () brackets in the url pattern.
Assuming the url you're matching requires additional arguments, take a look in the error message and first take a look if the value for the given arguments look to be correct.
If they aren't correct:
The value is missing or an empty string
This generally means that the value you're passing in doesn't contain the value you expect it to be. Take a look where you assign the value for it, set breakpoints, and you'll need to figure out why this value doesn't get passed through correctly.
The keyword argument has a typo
Correct this either in the url pattern, or in the url you're constructing.
If they are correct:
Debug the regex
You can use a website such as regexr to quickly test whether your pattern matches the url you think you're creating, Copy the url pattern into the regex field at the top, and then use the text area to include any urls that you think it should match against.
Common Mistakes:
Matching against the . wild card character or any other regex characters
Remember to escape the specific characters with a \ prefix
Only matching against lower/upper case characters
Try using either a-Z or \w instead of a-z or A-Z
Check that pattern you're matching is included within the patterns tried
If it isn't here then its possible that you have forgotten to include your app within the INSTALLED_APPS setting (or the ordering of the apps within INSTALLED_APPS may need looking at)
Django Version
In Django 1.10, the ability to reverse a url by its python path was removed. The named path should be used instead.
If you're still unable to track down the problem, then feel free to ask a new question that includes what you've tried, what you've researched (You can link to this question), and then include the relevant code to the issue - the url that you're matching, any relevant url patterns, the part of the error message that shows what django tried to match, and possibly the INSTALLED_APPS setting if applicable.
A very common error is when you get with arguments ('',). This is caused by something like this:
{% url 'view-name' does_not_exist %}
As does_not_exist doesn't exist, django evaluates it to the empty string, causing this error message.
If you install django-fastdev you will instead get a nice crash saying does_not_exist doesn't exist which is the real problem.
With django-extensions you can make sure your route in the list of routes:
./manage.py show_urls | grep path_or_name
If the route is missing you probably have not imported the application.
It may be that it's not loading the template you expect. I added a new class that inherited from UpdateView - I thought it would automatically pick the template from what I named my class, but it actually loaded it based on the model property on the class, which resulted in another (wrong) template being loaded. Once I explicitly set template_name for the new class, it worked fine.
The arguments part is typically an object from your models. Remember to add it to your context in the view. Otherwise a reference to the object in the template will be empty and therefore not match a url with an object_id.
Watch out for different arguments passing between reverse() and redirect() for example:
url(r"^some_app/(?P<some_id>\d+)/$", some_view_function, name="some_view")
will work with:
reverse("some_view", kwargs={"some_id": my_id})
and:
redirect("some_view", some_id=my_id)
but not with:
reverse("some_view", some_id=my_id)
and:
redirect("some_view", kwargs={"some_id": my_id})
I am trying to pass an entire, full length/structure URL within my app as an argument inside the app's URL. For example, I want to be able to do something like:
myapp.com/https://www.youtube.com/watch?v=dQw4w9WgXcQ so that I can take the URL entered after my app's home page and store it. However, I think the app is getting confused when the URL pasted has fragments and query arguments (ie: contains # and/or ?) My urls.py looks like this:
url(r'^(?P<url_param>[a-zA-Z0-9_.-/:?=#]*)/$', views.anywebsiteentered, name='anywebsiteentered')
When I try to write a view that looks like below to take the inputted URL and save it inside a model object, I always get the URL truncated before the query and fragment characters, what can I do so that my application picks up the entire URL string?
def anywebsiteentered(request, url_param = 'url_param'):
UrlBlob.objects.create(fullurl=url_param)
For example, the above object created if my app is at myapp.com/https://www.youtube.com/watch?v=dQw4w9WgXcQ only returns https://www.youtube.com/watch and not the query part of the URL. I suspect it is something I am doing with the passing of the URL because when I create this model object manually inside the python-django shell there is no problems at all.
Thanks for any help and hints. I really appreciate it.
If you needed to use some url in "path" area of another url you should escape it's special characters. For example use %3F instead "?". It's called url escaping.
For your purpose would be better pass url as argument like:
myapp.com/?url=http://www.youtube.com/watch?v=dQw4w9WgXcQ
— browser will do necessary escaping in this case.
You can get the query string from request.META:
def anywebsiteentered(request, url_param='url_param'):
full_url = url_param
query_string = request.META['QUERY_STRING']
if query_string:
full_url += u'?' + query_string
UrlBlob.objects.create(fullurl=full_url)