django - 修改Django "save and add another"按钮,根据刚保存的对象上的字段值设置字段的初始值

标签 django forms django-forms django-admin

我有一个带有模型条目和类别的基本博客应用程序。 Entry 中的字段之一是类别的外键。当用户添加一个条目并选择“保存并添加另一个”时,我希望新表单的类别设置为等于刚刚保存的对象的类别。

我怎样才能做到这一点?

最佳答案

this question 的帮助下解决了这个问题.诀窍是修改 response_addresponse_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/

相关文章:

python - Python、Django 和标准输出的奇怪问题

Django form.cleaned_data为None

python - Django:在文本文件中从 Model.save() 编写 SQL 代码

python - Django - 根据用户组过滤下拉选项

Angular (15) 无法扩展类型化的 FormGroup

java - 表单不会向 servlet 发布任何值

python - 如何在HTML音频源标签中链接Django模型的属性?

django - 带有可选信息的多对多多项选择表

python - Django 每月/每季度对 DateField() 数据进行分组

css - 使用 required 属性在 HTML5 输入字段上设置提示样式