In my Django application, I have a delete button to delete a particular file instance.
{% for file in file_list %}
<tr>
<td>{{ file.filename }}</td>
<td>
<!-- passing the file.pk argument to JS function -->
<a data-toggle="modal" href="#fileConfirmDeleteModal" data-id="{% url 'delete_file' file.pk %}">
<button class="btn btn-danger">Delete</button>
</a>
</td>
</tr>
{% endfor %}
In my JavaScript function call I am displaying the modal confirmation box to delete the file:
<script type="text/javascript">
$(document).on("click", ".open-AddBookDialog", function () {
var file_pk = $(this).data('id'); //the 'file.pk' instance is retrieved
//how to pass 'file_pk' argument to the <a href> tag in the modal
$(".modal-footer #delete_file_href").val( file_pk );
$('#fileConfirmDeleteModal').modal('show');
});
</script>
Below is the Modal dialog which contains a 'Yes' and 'No' button; on clicking 'Yes', a specific URL pattern needs to be called i.e. 'delete_file' file.pk
<!--Modal: fileConfirmDeleteModal-->
<div class="modal fade" id="fileConfirmDeleteModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<!--Content-->
<div class="modal-content text-center">
<!--Header-->
<p class="heading">Are you sure?</p>
<!--Body-->
<div class="modal-footer flex-center">
<!--Here I need to append the file.pk value to the 'delete_file url name'-->
<a href="{% url 'delete_file' file.pk=file_pk %}" id="delete_file_href">
<button>Yes</button>
</a>
<button class="btn btn-danger" data-dismiss="modal">No</button>
</div>
</div>
<!--/.Content-->
</div>
</div>
On attempting the above code, I encounter the following error:
Exception Type: TemplateSyntaxError at /mysite/file_log/
Exception Value: Could not parse the remainder: '=file_pk' from 'file.pk=file_pk'
The urlpattern being:
path('delete_file/<int:pk>', views.FileDeleteView.as_view(), name='delete_file'),
I am unable to understand how to append that variable value 'file_pk' to inside the url name {% %} of href tag.
答案 0 :(得分:0)
对于模板错误,应首先写出参数名称(file_pk
),然后写值(file.pk
):
{% url 'delete_file' file_pk=file.pk %}
对于modale问题,您可以在第一个模板中将删除URL作为data-delete-url
参数进行传递:
{% for file in file_list %}
<tr>
<td>{{ file.filename }}</td>
<td>
<!-- passing the file.pk argument to JS function -->
<a data-toggle="modal" href="#fileConfirmDeleteModal"
data-id="{{ file.pk }}" data-delete-url="{% url 'delete_file' file_pk=file.pk %}">
<button>Delete</button>
</a>
</td>
</tr>
{% endfor %}
然后使用以下值更新modale URL:
<script type="text/javascript">
$(document).on("click", ".open-AddBookDialog", function () {
var delete_url = $(this).data('delete-url');
$(".modal-footer #delete_file_href").prop( delete_url );
$('#fileConfirmDeleteModal').modal('show');
});
</script>