Passing a parameter through AJAX URL with Django

2024/9/25 17:11:14

Below is my code. 'n' logs correctly in the console, and everything works perfectly if I manually enter the value for 'n' into url: '{% url "delete_photo" iddy=2%}'. Alas, when I try to use 'n' as a variable (seen below) it gives me a reverse match not found error. Can anyone help with this?

javascript

 function test(n){console.log(n);$.ajax({type: 'get',url: '{% url "delete_photo" iddy=n%}',datatype:'json',success: function(data){alert(n)console.log(data)console.log(n)},error: console.log("SSS"),});}

html

{% for t in photos %}
<div id="photobox" ><img id="img_pb3"src="{{t.photo.url}}">
<div><a><span onclick="test({{t.id}})" class="closeBtn">&times;</span></div></a>
</div>
{% endfor %}

urls

urlpatterns = [path('', views.explore, name='explore'),path('home/', views.home, name='home'),path('home/comment', views.comment, name='comment'),path('home/photo_del/<iddy>', views.delete_photo, name='delete_photo')
]

views

def delete_photo(request, iddy):data = {'a':iddy, 'b': iddy}return JsonResponse(data, safe=False)
Answer

You can't possibly do this. You have fundamentally misunderstood the relationship between backend Django code and front-end Javascript code. Django templates are fully evaluated on the server, at which point the template tags are converted into plain HTML text. There is therefore no way that a Javascript function - which runs much, much later, on the browser itself - can pass a parameter to be used in a template tag.

The only way to do this would be to render the URL with a dummy value - one you know can't occur in the URL itself - and then replace that value in the JS with the one from the parameter, using normal JS string replace functions.

To be honest, it would be better to remove the ID from the URL altogether. Apart from anything else, a delete action should be a POST, not a GET - you don't want the Googlebot accidentally crawling your URLs and deleting all your items - and with a POST you can send the ID in the posted data.

https://en.xdnf.cn/q/71551.html

Related Q&A

WARNING: toctree contains reference to nonexisting document error with Sphinx

I used the sphinx-quickstart to set everything up. I used doc/ for the documentation root location. The folder containing my package is setup as: myfolder/doc/mypackage/__init__.pymoprob.py...After the…

Removing nan from list - Python

I am trying to remove nan from a list, but it is refusing to go. I have tried both np.nan and nan.This is my code:ztt = [] for i in z:if i != nan:ztt.append(i) zttor:ztt = [] for i in z:if i != np.nan…

Safely unpacking results of str.split [duplicate]

This question already has answers here:How do I reliably split a string in Python, when it may not contain the pattern, or all n elements?(5 answers)Closed 6 years ago.Ive often been frustrated by the…

Get a structure of HTML code

Im using BeautifulSoup4 and Im curious whether is there a function which returns a structure (ordered tags) of the HTML code. Here is an example:<html> <body> <h1>Simple example</h…

max_help_position is not works in python argparse library

Hi colleagues I have the code (max_help_position is 2000):formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=2000) parser = argparse.ArgumentParser(formatter_class=formatter_cl…

Python - How to parse argv on the command line using stdin/stdout?

Im new to programming. I looked at tutorials for this, but Im just getting more confused. But what Im trying to do is use stdin and stdout to take in data, pass it through arguments and print out outpu…

Bad Request from Yelp API

Inspired by this Yelp tutorial, I created a script to search for all gyms in a given city. I tweaked the script with these updates in order to return ALL gyms, not just the first 20. You can find the g…

Python: test empty set intersection without creation of new set

I often find myself wanting to test the intersection of two sets without using the result of the intersections.set1 = set([1,2]) set2 = set([2,3]) if(set1 & set2):print("Non-empty intersection…

object has no attribute show

I have installed wxpython successfully which i verified by import wxBut when I write a code import wx class gui(wx.Frame):def __init__(self,parent,id):wx.Frame.__init__(self, parent,id,Visualisation fo…

How Does Calling Work In Python? [duplicate]

This question already has answers here:Does Python make a copy of objects on assignment?(5 answers)How do I pass a variable by reference?(40 answers)Why can a function modify some arguments as percei…