Django admin:单击ForeignKey下拉菜单旁边的add-another按钮时预填充数据 [英] Django admin: Prefill data when clicking the add-another button next to a ForeignKey dropdown

查看:130
本文介绍了Django admin:单击ForeignKey下拉菜单旁边的add-another按钮时预填充数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django Admin中,当您修改对象属性时,如果有一个ForeignKey,它将具有一个包含所有选项的下拉框,以及一个 +按钮以添加更多选择。当我单击它时,我想预填充一些数据。

In the Django Admin, when you modify an objects properties, if there is a ForeignKey, it will have a dropdown box of all the choices, plus a "+" button to add more choices. When I click on it, I want to prefill some of the data.

我注意到,如果可以修改URL,我可以做到(例如: http:// localhost:8000 / admin / app / model / add /?field = value 其中, field value 是通过程序修改的。)

I've noticed I could do it if I could modify the URL (example: http://localhost:8000/admin/app/model/add/?field=value where field and value are programmatically modified.)

我认为我必须重写 forms.ModelForm admin.ModelAdmin 使用的code>,但我不确定。

I figure I have to override something in the forms.ModelForm that the admin.ModelAdmin uses, but I'm not sure what.

推荐答案

Django允许您替换请求的GET dict(它用于预填充管理表单)。

Django allows you to replace a request's GET dict (which it uses to pre-populate the admin form).

Django会自动填充URL GET参数中的值如果要在URL中发送模型形式的字段值。

Django will automatically fill values from URL GET parameters if you are sending field values of model form in the URL.

例如,考虑
http:// myhost / admin / app / model / add /?name = testname ,它将在管理员添加视图模板中的表单的 name 字段中预先填充值测试名

For example, considering "http://myhost/admin/app/model/add/?name=testname", it will prefill the name field of the form in the admin add-view template with the value 'testname'.

但是,如果您发送的是网址中的ny id,您需要通过覆盖 add_view 函数来修改GET参数。

But, if you are sending any id in your URL, you need to modify the GET parameters by overriding the add_view function.

来自stackoverflow答案

Taken from stackoverflow answer

class ArticleAdmin(admin.ModelAdmin):
    // ...

    def add_view(self, request, form_url='', extra_context=None):
        source_id = request.GET.get('source',None)
        if source_id != None:
            source = FeedPost.objects.get(id=source_id)
            // any extra processing can go here...
            g = request.GET.copy()
            g.update({
                'title':source.title,
                'contents':source.description + u"... \n\n[" + source.url + "]",
            })

            request.GET = g

        return super(ArticleAdmin, self).add_view(request, form_url, extra_context)

这只是一个示例,请使用您的模型和字段进行操作:)

It just an example.DO it with Your model and fields :)

这篇关于Django admin:单击ForeignKey下拉菜单旁边的add-another按钮时预填充数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆