我有一个Django模型,我想为其添加自定义操作。在此操作中,我需要在其中添加一个带有选择表单的中间页面(下拉选择)。我用下面的代码来做到这一点。
型号类别:
class VerificationAdmin(admin.ModelAdmin):
list_display = ('id','asset_code', 'scan_time','credential','status','operator','location','auth_code','product_details')
list_filter = ('status','operator','location')
ordering = ('-scan_time',)
search_fields = ('asset_code',)
actions = ['set_interval']
class AddScanningIntervalForm(forms.Form):
_selected_action = forms.CharField(widget=forms.MultipleHiddenInput)
period_choice=["4 hrs","6 hrs","8 hrs","10 hrs","12 hrs"]
interval = forms.ChoiceField(choices=[(x, x) for x in period_choice])
@csrf_exempt
def set_interval(self, request, queryset):
print "before action"
form = None
if 'apply' in request.POST:
form = self.AddScanningIntervalForm(request.POST)
print "action taken"
if form.is_valid():
interval = form.cleaned_data['interval']
print interval
count = 0
for vObj in queryset:
print vObj.asset_code,vObj.status,interval
at=AlertTable(asset_code=vObj.asset_code,
status=vObj.status,interval=interval)
at.save()
count += 1
self.message_user(request, "Scanning Policy Successfully added to %s assets %s." %count)
return HttpResponseRedirect(request.get_full_path())
if not form:
form = self.AddScanningIntervalForm(initial={'_selected_action': request.POST.getlist(admin.ACTION_CHECKBOX_NAME)})
return render_to_response('admin/set_alert.html', {'verifications': queryset,'tag_form': form},context_instance=RequestContext(request))
set_interval.short_description = "Add Periodic Scanning Policy"
添加模板部分:
<!DOCTYPE html>
{% extends "admin/base_site.html" %}
{% block content %}
<p>Select tag to apply:</p>
<form action="" method="post">
{{ tag_form }}
{% csrf_token %}
<p>The scanning policy will be applied to:</p>
<ul>{{ verifications|unordered_list }}</ul>
<input type="hidden" name="action" value="add_tag" />
<input type="submit" name="apply" value="Set Interval" />
</form>
{% endblock %}
直到“中间”页面都可以正常工作,但是在中间页面的表单中选择了一个警报选项并单击“设置间隔”按钮后,我得到的结果是“未选择任何操作”
最佳答案
这个问题有点老了,但是可以将来引用。确保中间形式中的“操作”输入属性与管理功能名称匹配。在这种情况下,使用“set_interval”代替“add_tag”。
POST上下文还必须包含“_selected_action”值,该值应与所选项目pk匹配。
关于添加中间表单后,Django管理站点操作不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23167923/