简体   繁体   中英

django: passing a url as a parameter

I want to pass a URL from javascript to a django view. I have the following urls.py

     --- urls.py ---
     url(r'^show/(?P<url>\.+)$', 'myapp.views.jsonProcess'),

The view has the following declaration:

    --- views.py ---
    def jsonProcess(request, url):

The URL I pass in javascript is as follows:

    url = 'http://127.0.0.1:8000/show/' + 'http://www.google.com';
    window.open(url);

I get a "Page not Found (404)" error while matching the URL. What am I missing? Any, and all pointers are welcome since I am hopelessly stuck! :(

Firstly, you don't need to escape the dot if you want it to mean any symbol (in urls.py ).

url(r'^show/(?P<url>.+)$', 'myapp.views.json_process')

Secondly, use encodeURIComponent to properly escape the parameter.

var url = 'http://127.0.0.1:8000/show/' +
    encodeURIComponent('http://www.google.com')

By the way, don't use mixedCase for function names in Python:

Function names should be lowercase, with words separated by underscores as necessary to improve readability.


Another note that might help in future: don't hardcode Django URLs in JavaScript. You can generate them dynamically either in your views :

from django.core.urlresolvers import reverse
url = reverse(
    'myapp.views.json_process',
    kwargs={'url': 'http://www.google.com'}
)

Or in templates :

{% url myapp.views.json_process url="http://www.google.com" %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM