具有中间页面的Django管理员操作:未获取信息 [英] Django admin action with intermediate page: not getting info back
问题描述
我正在尝试创建一个管理员操作,以将自定义时间增量添加到某个日期。时间增量将从中间页面的输入中读取。确认之后,我会将那个增量应用于先前选择的每个实例。使用此代码(我对此问题进行了简化),我无法获得输入时间增量的值。我无法判断用户是否按下了应用按钮。
I'm trying to create an admin action that adds a custom time delta to some date. The time delta will be read from a input in the intermediate page. After confirming it, I will apply that delta to every instance selected previously. Using this code (I simplified for this question) I can't get the value of the entered time delta. I can't tell whether the user pressed the "Apply" button.
models.py
models.py
class Match(models.Model):
date_of_match=models.DateTimeField()
admin.py
class MatchAdmin(admin.ModelAdmin):
actions=('move_date',)
def move_date(self,request,queryset):
if 'apply' in request.POST:
#to do, add timedelta to date_of_match
print("I'M IN!")
return render(request.'admin/move_date.html',{'matches':queryset})
move_date.short_description="Move date"
move_date.html
move_date.html
{% extends "admin/base_site.html" %}
{% block content %}
<form action="" method="post">{% csrf_token %}
<p>How much delta?<p>
<input type="number" step="1" value="days"/>
<input type="hidden" name="action" value="move_date" />
<input type="submit" name="apply" value="Apply"/>
</form>
{% endblock %}
推荐答案
可能也是来帮助OP的时间很晚,但是当遇到相同的问题时,我遇到了这个问题,并且在其他地方看不到发生了什么。
Probably too late to help OP, but I came across this question when having the same issue and it was not immediately obvious looking elsewhere what was going on.
当 changelist_view
已处理(我们正在 POST
进入的视图),它出现在 request.POST $ c中$ c>作为特定键:
_selected_action
在 django.contrib.admin.helpers
中定义为 ACTION_CHECKBOX_NAME
。我使用了内置于admin中的delete动作作为参考,它在模板中以这种方式使用它:
When the changelist_view
is processed (the view we are POST
ing to) it looks in request.POST
for a specific key: _selected_action
which is defined in django.contrib.admin.helpers
as ACTION_CHECKBOX_NAME
. I used the delete action that is built into the admin for reference, and it uses it this way in the template:
{% for obj in queryset %}
<input type="hidden" name="{{ action_checkbox_name }}" value="{{ obj.pk|unlocalize }}">
{% endfor %}
然后在您的上下文中,您只需要:
then in your context you just need to:
context = {
'queryset': queryset, # method param
'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
}
现在,当您 POST
您的表单,您可以在此处尝试检测/处理 POST
。 (您想从处理您的 POST
数据的块中返回 None
,以便视图知道返回到列表视图。)
Now your method gets called again when you POST
your form, and you can detect/handle the POST
as you're trying to do here. (You want to return None
from the block that handles your POST
data so the view knows to go back to the list view.)
这篇关于具有中间页面的Django管理员操作:未获取信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!