我有兴趣为管理界面创建一个操作,该操作需要除所选项目之外的一些附加信息。我的示例是将漫画批量添加到系列中。 (是的,我知道明显的答案是创建一个具有 X-to-X 关系的模式,但请耐心听我讲一个简单的例子)。
在此示例中,我创建了 100 幅漫画。创建它们后,我想将它们与已创建的系列对象相关联。要在管理员中执行此操作,我想选择项目然后启动该操作。然后我应该被问到要使用哪个系列对象(通过弹出窗口、中间表单等)。
我已按照说明 here 进行操作声称通过中间形式来实现这一点。使用它之后,我没有再收到任何错误,但操作本身也没有被执行 - forloop 永远不会被执行。相反,它会返回漫画管理列表,并显示消息:“未选择任何操作。”
我的admin.py方法:
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
def addSeries(self, request, queryset):
form = None
if 'cancel' in request.POST:
self.message_user(request, 'Canceled series linking.')
return
elif 'link_series' in request.POST:
form = self.SeriesForm(request.POST)
if form.is_valid():
series = form.cleaned_data['series']
for x in queryset:
y = Link(series = series, comic = x)
y.save()
self.message_user(request, self.categorySuccess.render(Context({'count':queryset.count(), 'series':series})))
return HttpResponseRedirect(request.get_full_path())
if not form:
form = self.SeriesForm(initial={'_selected_action': request.POST.getlist(admin.ACTION_CHECKBOX_NAME)})
return render_to_response('setSeries.html', {'comics': queryset, 'form': form, 'path':request.get_full_path()}, context_instance=RequestContext(request))
addSeries.short_description = 'Set Series'
我的中间表单setSeries.html:
<!DOCTYPE html>
<html>
<head>
<title>Create Series Links</title>
</head>
<body>
<h1>Create Series Links</h1>
<p>Choose the series for the selected comic(s):</p>
<form method="post" action="{{ path }}">
<table>
{{ form }}
</table>
<p>
<input type="hidden" name="action" value="changeSeries" />
<input type="submit" name="cancel" value="Cancel" />
<input type="submit" name="link_series" value="link_series" />
</p>
</form>
<h2>This categorization will affect the following:</h2>
<ul>
{% for comic in comics %}
<li>{{ comic.title }}</li>
{% endfor %}
</ul>
</body>
</html>
最佳答案
我注意到的一件事是,您的操作方法是“addSeries”,但在形式中您将其称为“changeSeries”。
在您的 ModelAdmin 中,您应该有这样一行:
actions = ['addSeries']
如果您有这样的行,那么您需要更改:
<input type="hidden" name="action" value="changeSeries" />
至:
<input type="hidden" name="action" value="addSeries" />
这就是 Django 管理员如何知道选择了哪个操作。当您在选择操作和执行操作之间有一个中间表单时,您需要从管理界面的选择菜单中保留操作名称。
关于django - 如何创建需要额外信息的复杂管理操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3605185/