在我的Django应用程序中,我想实现一个中间页面,在执行特定的管理操作之前要求确认。我以this post为例。
我使用现有的delete_confirmation.html
模板作为起点,部分使其正常运行。将显示确认页面,并显示所选对象。但是,点击“是的,我确定”后,我的管理员操作永远不会被调用。
在我的admin.py中,我有:
def cancel_selected_bookings(self, request, queryset):
"""
Cancel selected bookings.
"""
if request.POST.get("post"):
for booking in queryset:
booking.cancel()
message = "Booking %s successfully cancelled." % booking.booking_id
messages.info(request, message)
else:
context = {
"objects_name": "bookings",
'title': "Confirm cancellation of selected bookings:",
'cancellable_bookings': [queryset],
'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
}
return TemplateResponse(request, 'admin/bookings/confirm_cancel.html', context, current_app=self.admin_site.name)
在我的模板中(剪辑完整模板):
<div class="grp-group">
<h2>
{% blocktrans %}
Are you sure you want to cancel the selected {{ objects_name }}?
{% endblocktrans %}
</h2>
{% for cancellable_booking in cancellable_bookings %}
<ul class="grp-nested-list">{{ cancellable_booking|unordered_list }}</ul>
{% endfor %}
</div>
<form action="" method="post">{% csrf_token %}
<div id="submit" class="grp-module grp-submit-row grp-fixed-footer">
{% for obj in queryset %}
<input type="hidden" name="{{ action_checkbox_name }}" value="{{ obj.pk|unlocalize }}" />
{% endfor %}
<input type="hidden" name="action" value="cancel_selected_bookings" />
<input type="hidden" name="post" value="yes" />
<ul>
<li class="grp-float-left"><a href="." class="grp-button grp-cancel-link">{% trans "Cancel" %}</a></li>
<li><input type="submit" value="{% trans "Yes, I'm sure" %}" class="grp-button grp-default" /></li>
</ul>
<input type="hidden" name="post" value="yes" />
</div>
</form>
修改
我在上面的模板中发现了一个问题。这些行:
{% for obj in queryset %}
<input type="hidden" name="{{ action_checkbox_name }}" value="{{ obj.pk|unlocalize }}" />
{% endfor %}
需要替换为:
{% for cancellable_booking in cancellable_bookings %}
<input type="hidden" name="{{ action_checkbox_name }}" value="{{ cancellable_booking.id }}" />
{% endfor %}
但是出于一些神秘的原因,隐藏字段的值不是由{{cancellable_booking.id}}
设置的。当我使用现有ID进行硬编码时,它都按预期工作。我做错了什么?
答案 0 :(得分:2)
这将有效:
在动作方法中:
context = {
'objects_name': 'bookings',
'title': 'Confirm cancellation of selected bookings:',
'cancellable_bookings': [queryset],
'ids': queryset.values_list("id"),
'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
}
在模板中:
{% for id in ids %}
<input type="hidden" name="{{ action_checkbox_name }}" value="{{ id.0|unlocalize }}" />
{% endfor %}
不确定为什么迭代queryset
不起作用,但唉...