我有一个带有模型条目和类别的基本博客应用程序。 Entry 中的字段之一是类别的外键。当用户添加一个条目并选择“保存并添加另一个”时,我希望新表单的类别设置为等于刚刚保存的对象的类别。
我怎样才能做到这一点?
最佳答案
在 this question 的帮助下解决了这个问题.诀窍是修改 response_add
和 response_change
ModelAdmin
的方法
class EntryAdmin(admin.ModelAdmin):
...
def response_add(self, request, obj, post_url_continue=None):
if request.POST.has_key('_addanother'):
url = reverse("admin:blog_entry_add")
category_id = request.POST['category']
qs = '?category=%s' % category_id
return HttpResponseRedirect(''.join((url, qs)))
else:
return HttpResponseRedirect(reverse("admin:blog_entry_changelist"))
def response_change(self, request, obj, post_url_continue=None):
if request.POST.has_key('_addanother'):
url = reverse("admin:blog_entry_add")
category_id = request.POST['category']
qs = '?category=%s' % category_id
return HttpResponseRedirect(''.join((url, qs)))
else:
return HttpResponseRedirect(reverse("admin:blog_entry_changelist"))
对于 Python 3,替换
if request.POST.has_key('_addanother'):
和
if '_addanother' in request.POST:
关于django - 修改Django "save and add another"按钮,根据刚保存的对象上的字段值设置字段的初始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14067341/