How can I pass a javascript variable to a Django URL? It presents a,
TypeError at /object/Query/details
view() got an unexpected keyword argument 'query'
I am trying to redirect to another HTML page following this process:
HTML Search Input > Pass to Javascript through input button onclick > Pass to JQuery Ajax sendQueryData> Redirect to another page using Django render()
;considering I had to do more things on the passed parameters to the URL upon passing them in AJAX.
The main problem lies on this two lines (I think):
url_page = url + "{% url 'view' 'query'%}"; //supposedly how we get parameters (but query is a javascript `var`
and
url =url.replace('query' , query); //where I intend to correctly build the url forcing the query to take its place in the url
I'm just not quite sure if my urls.py, ajax call on javascript in Django url are all aligned at all.
My urls.py
urlpatterns = [
url(r'^$', views.index, name='homepage'),
#--- Home ---
url(r'^search/pass/$', views.pass_query, name='pass_query'),
# View Object Details
url(r'^object/(?P<query>\w+)/details', views.view(), name='view')
My HTML
<div id="button-group" class="button-group">
<input type="submit" class="btn btn-primary btn-lg btn-space col-sm-3" onclick="redirect_to_url(0)" value="View Inventory"/>
<input type="submit" class="btn btn-primary btn-lg btn-space col-sm-3" onclick="redirect_to_url(1)" value= "View Details"/>
Javascript
function redirect_to_url(to_page){
var query = document.getElementById("search").value;
var url = document.URL;
url = url.slice(0, -1);
if (to_page === 0) {
url_page = url + "{% url 'view' 'query'%}";
sendQueryData(url_page, query);
}
else if(to_page === 1) {
url_page = url + "{% url 'another_view' 'query' %}";
sendQueryData(url_page, query);
}
return false;
}
function sendQueryData(url, query){
url =url.replace('query' , query);
if (query === ""){
alert("Input Required");
}else{
$.ajax({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
type: "POST",
url: "/search/pass/",
data: {
'query' : query,
'url' : url
},
success: function(result){
alert(result);
window.location.href = url;
}
});
}
}
Views.py
def pass_query(request):
query =request.POST['query']
print(query)
return HttpResponse(query)
def view(request):
return render(request, 'plexus/view.html')
Edit:
The error occurs at AJAX Success function. If I debugged it correctly, I tried to change the url in
window.location.href =to another static URL that doesn't have a parameter unlikeurl(r'^object/(?P<query>\w+)/details', views.view, name='view'),and it does work well. If this is so, maybe I can re-title this on how to add a parameter to the url where Django URL is looking for an argument.
views.view?render()I'm going to re-do the question a bit, since it since that I'm having a problem how to add a parameter on template load