Reiion Reiion - 1 month ago 5
Ajax Question

python url not found - Accessing views.py from AJAX

New to Python and Django and I'm trying to make a simple ajax call from a button click to pass certain data to my views.py, however, when I try to make a url as seen on my ajax code below, the

documentId.id
does not append unless I directly append in without the
"?id="
.

{%for document in documents%}
{{document.filename}}
<input type="button" id="{{document.id}}" onclick="loadData(this)" name="load-data" value="Add"/>
{%endfor%}

<script type ="text/javascript">
function loadData(documentId){
$.ajax({
url:"upload-data/load" + "?id=" + documentId.id,
data: {'documentId': documentId},
type: 'GET',
success: function(){
window.location.href = "http://127.0.0.1:8000/url/locations";
}
});
}
</script>


This gives me then an error that says the url cannot be found. I have a line in my urls.py below:

url(r^"upload-data/load/([0-9]+)/$', views.loadFile, name="load-data"),


Other than this method, I am stumped as to how I am going to extract my data to my views.py.

def loadFile(request):
documentId = request.GET.get('id')
newLayer = Layer(get_object_or_404(Document, pk = documentId))
newLayer.save()
layers = Layer.objects.all()

return render(request, 'url/loaded.html', { 'layers': layers})


The persisting error in the console would be:


http://127.0.0.1:8000/upload-data/load/ [HTTP/1.0 404 Not Found]

Answer

Use something like this:

def loadFile(request):
    documentId= request.GET.get('id', '').
    newLayer = Layer(get_object_or_404(Document, pk = documentId))
    newLayer.save()
    layers = Layer.objects.all()

    return render(request, 'url/loaded.html', { 'layers': layers})

And update your url as :

    url(r^"upload-data/load/', views.loadFile, name="load-data")

And the script would be like :

<script type ="text/javascript">
    function loadData(documentId){
       $.ajax({
       url:"upload-data/load/?id="+ documentId.id,
       data: {'documentId': documentId},
       type: 'GET',
       success: function(){
          window.location.href = "http://127.0.0.1:8000/url/locations";
       }
    });
    }
 </script>

Thanks.

Comments