问题
I am using jquery datatables in my django app. every row in my table have a named url to another page together with the object.
{% url 'obj_details' obj.id %}
. When I click on the url I am getting no reverse match found error. I have inspected the issue in detail. The url obj_details is a named url that exists in the urls.py
url(r'^obj/(?P<pk>[\w-]+)/details$', objDetailsView.as_view(), name='obj_details')
datatables uses another view to get the required data it is as pasted below
def objdtable(request):
obj_json_tuple = list(Obj.objects.all().values_list("objnum", "ob_field", "date", "price", "field2", "seller", "id"))
return HttpResponse(json.dumps(obj_json_tuple))
I am displaying all fields except id in datatables without issues.
"columns": [
{ "": "fields.objnum"},
{ "": "fields.ob_field" },
{ "": "fields.date" },
{ "": "fields.price" },
{ "": "fields.field2" },
{ "": "fields.seller" },
]
How can I pass id returned by objdtable view as an argument to url obj_details? I have tried {% url 'obj_details' fields.id %}
and {% url 'obj_details' id %}
but bothe are giving no reverse match found errors. Then I tried in datatables
"data":
{
'bid':fields.id
}
and changed the named url to the link obj/data/details
I have also tried changing data to fields.id but nothing worked. How can I access a variable passed by django in datatables? I can use that variable in url so that the issue could be solved.
PS:On changing url to url(r'^/obj/(?P<pk>\d+)/details$, objDetailsView.as_view(), name='obj_details')
but its giving me the no reverse match found error as pasted below.
NoReverseMatch at /myapp/obj/list/Reverse for 'obj_details' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['myapp/obj/(?P<pk>\\d+)/details$']
The error in html template is in the line pasted below.
"defaultContent": "<a class='btn btn-success btn-sm' href="{% url 'obj_details' id %} " style='color:white'> <i class='fa fa-eye fa-lg'></i> </a>"
回答1:
Your issue is that you're trying to use a jQuery variable to render a Django URL.
The Object JSON data is jQuery, so you can't use it on your {% url 'obj_details' id %}
call.
When I faced an issue like that I do something like this:
<script>
// Let's supose you have your jQuery ID value here
var id = yourdict.obj.id;
// Now you have the ID inside a jQuery variable you can do this
// Generate an URL with an aux ID '000'
var URL = "{% url 'obj_details' 000 %}"
URL = URL.replace('000', id) // Replace the aux ID with the real one
</script>
来源:https://stackoverflow.com/questions/30069338/get-variables-in-datables-passed-by-django