Django: Capturing data from URL will not work - python

I have the following statement in my URL.py file
(r'^confirm/(\d+)/$', confirm)
But this URL
http://127.0.0.1:8000/confirm/DMo32zPB15
Returns this
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/confirm/DMo32zPB15
Using the URLconf defined in BBN.urls, Django tried these URL patterns, in this order:
^login/$
^ajax/login$
^ajax/login/nact/$
^ajax/login/nact/cancel//$
^ajax/login/nact/resend/$
^confirm/(\d+)/$
The current URL, confirm/DMo32zPB15, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file Change that to False, and Django will display a standard 404 page.
Why won't it regognize the URL?

\d+ means one or more digits.
DMo32zPB15 has both digits and letters. Try r'^confirm/([a-zA-Z0-9]+)/$' instead.
More information about regular expressions can be found at http://www.regular-expressions.info for your reading pleasure.

This is related to your other question about \d+. \d+ matches only digits. Your URL contains things that are not digits (like letters). You should take a look at the regex tutorial I linked in my answer to your other question and get a solid grasp of regular expressions before you try to write URL matchers using them.

Related

Route's with a leading/traling slash and without slashes

Could you please explain to me the diffference between:
#app.route( '/something' )
compared to:
#app.route( 'something/' )
and also compared to:
#app.route( 'something' )
So i can better distinguish them?
In a word, /foo was the normal use case, /foo/ was used when you want to make the URL looks like a path/folder, foo was wrong. If I'm wrong, please correct me.
The URL rule should start with a slash(/).
/foo and /foo/ was two different URL rule, see the details in the docs:
The following two rules differ in their use of a trailing slash.
#app.route('/projects/')
def projects():
return 'The project page'
#app.route('/about')
def about():
return 'The about page'
The canonical URL for the projects endpoint has a trailing slash. It’s similar to a folder in a file
system. If you access the URL without a trailing slash, Flask
redirects you to the canonical URL with the trailing slash.
The canonical URL for the about endpoint does not have a trailing
slash. It’s similar to the pathname of a file. Accessing the URL with
a trailing slash produces a 404 “Not Found” error. This helps keep
URLs unique for these resources, which helps search engines avoid
indexing the same page twice.
Link: http://flask.pocoo.org/docs/1.0/quickstart/#unique-urls-redirection-behavior

Django url warning urls.W002

Sorry in advance if this question look a bit superfluous but is something that is really bothering me.
I have a set of API's written in Django defined by the following urls.
# urls.py
import ...
urlpatterns = [
url(r"^api/v1/account", include(profile.urls))
]
and
# profile/urls.py
import ...
urlpatterns = [
url(r"^$", AccountAPI.as_view()),
url(r"^/login$", LoginAPI.as_view()),
url(r"^/logout$", LogoutAPI.as_view())
]
This configuration should allow only the urls:
/api/v1/account
/api/v1/account/login
/api/v1/account/logout
This work for my purpose but I keep having warnings like(I have several API defined with this rule and the warning list is way bigger):
?: (urls.W002) Your URL pattern '^/login$' has a regex beginning with a '/'. Remove this slash as it is unnecessary.
?: (urls.W002) Your URL pattern '^/logout$' has a regex beginning with a '/'. Remove this slash as it is unnecessary.
If I remove the slash the server will not validate the urls I defined. For that I have to had a slash to the first level of the urls like:
# urls.py
import ...
urlpatterns = [
url(r"^api/v1/account/", include(profile.urls))
]
And this will make the account call to end with a slash, something I don't want to.
I feel that I have defined the urls the most elegant way I found to serve my purpose and I keep having this sad warnings in my logs.
Am I doing something wrong? Is there a right way to define the url's without compromising the structure I choose for them? Or there's a way of turning this warnings off?
You can turn the warning(s) off using SILENCED_SYSTEM_CHECKS option.
Example:
SILENCED_SYSTEM_CHECKS = ['urls.W002', 'security.W019']
When I wrote the check, I incorrectly assumed urls with trailing slashes, like /api/v1/account/ and /api/v1/account/login/.
If you do not use trailing slashes, then starting an included url pattern with ^/ can be correct, and the W002 check gives a false positive.
As of Django 1.10.2, the check is disabled if you have APPEND_SLASH=False in your settings. See ticket 27238 for the discussion.
this will make the account call to end with a slash, something I don't want to.
Why? Is there any specific reason?
As far as Django is concerned, there's nothing incorrect in ending a url with a slash. Moreover, Django's admin urls end in a slash. Django polls tutorial also appends slash to root URLconfs.
If you read URL Dispacher example, it says:
There’s no need to add a leading slash, because every URL has that. For example, it’s ^articles, not ^/articles.

How to match begin URL with REGEX in Django

I'm using this syntax for my API urls:
http://myhost/myapiname/X-Y-Z/web-service-name/
In Django urls.py, it looks like this:
url(r'api_s/2-0-0/get_client_profile/$', GetClientProfile.as_detail(), name='get_client_profile'),
Now, I'd like to redirect all 1-0-0 urls (deprecated webservices) to a specific view.
I tried something like url(r'api_t/1-0-0*$', Deprecated.as_list(), name='deprecated') but it can't be catch. I'm not used to REGEX so I'm missing something here. Thanks.
Add a dot before *:
url(r'api_t/1-0-0.*$', Deprecated.as_list(), name='deprecated')
The asterisk * sign means "repeat previous symbol zere or more times". The dot . means "any char". So .* will match any string.

Urls.py unable to pass #(pound) character to a view in Django,

I used to pass data through django URL while passing #character is not able to pass through urls.py, I am using pattern as
url(r'^pass/(?P<sentence>[\w|\W]*)/$',pass)
I tried with these pattern also
url(r'^pass/(?P<sentence>[a-zA-Z0-9-/:-?##{-~!^_\'\[\]*]*)/$',pass)
Thanks in advance.
The "#" character marks inline anchors (links within the same page) in a URL, so the browser will never send it to Django.
For example, if the URL is /something/pass/#test/something-else/ the browser will sent only /something/pass/ to the server. You can try /something/pass/%23test/something-else/ instead, 23 is the hexadecimal ascii code for # - not pretty (ugly by ugly just pass it as a get variable instead).
There is nothing you can do on the Django side - you better avoid characters with special meanings in the URL path when designing your routes - of course it is a matter of taste, but I really think that strings passed in the URL path should be "slugfied" in order to remove any funny character.
Browsers won't send the url fragment part (ends with "#") to servers. Why not converting your data to base64 first, then pass the data via url.
RFC 1808 (Relative Uniform Resource Locators) : Note that the fragment identifier (and the "#" that precedes it) is
not considered part of the URL. However, since it is commonly used
within the same string context as a URL, a parser must be able to
recognize the fragment when it is present and set it aside as part of
the parsing process.

Using URLS that accept slashes as part of the parameter in Django

Is there a way in Django to accept 'n' parameters which are delimited by a '/' (forward slash)?
I was thinking this may work, but it does not. Django still recognizes forward slashes as delimiters.
(r'^(?P<path>[-\w]+/)$', 'some.view', {}),
Add the right url to your urlpatterns:
# ...
("^foo/(.*)$", "foo"), # or whatever
# ...
And process it in your view, like AlbertoPL said:
fields = paramPassedInAccordingToThatUrl.split('/')
Certainly, Django can accept any URL which can be described by a regular expression - including one which has a prefix followed by a '/' followed by a variable number of segments separated by '/'. The exact regular expression will depend on what you want to accept - but an example in Django is given by /admin URLs which parse the suffix of the URL in the view.

Categories