添加中间表单后,Django管理站点操作无法正常工作

时间:2014-04-19 08:49:31

标签: django django-models django-admin

我有一个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 %}

它工作正常到中级页面,但在中间页面中选择表格中的一个警报选项并点击设置间隔按钮后我得到结果“未选择任何操作”

1 个答案:

答案 0 :(得分:2)

这个问题有点陈旧,但未来有任何参考;确保中间表单中的'action'输入属性与admin函数名称匹配。在这种情况下,'set_interval'而不是'add_tag'。

POST上下文也必须包含“_selected_action”值,这些值应与所选项目pks匹配。