问题
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
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
{% 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 %}
回答1:
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.
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,
}
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.)
来源:https://stackoverflow.com/questions/52845346/django-admin-action-with-intermediate-page-not-getting-info-back