3

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! :(

1 Answer 1

6

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" %}
Sign up to request clarification or add additional context in comments.

2 Comments

That worked! I was escaping the dot. Thank you! :) I'll keep the naming convention in mind... I'm relatively new to python!
what if for example I'd like to pass a parameter that is a javascript? ` var query = document.getElementById("search").value; url_page = url + "{% url 'city_view' query=query%}";`

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.