Django admin:如何从 GET 变量中填充新对象? [英] Django admin: How to populate a new object from GET variables?

查看:16
本文介绍了Django admin:如何从 GET 变量中填充新对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Django 的管理员中,我看到了如何使用 GET 变量设置添加对象"表单的字段(例如 /admin/app/model/add?title=lol 设置标题"字段改为大声笑").

In Django's admin, I've seen how I can set the fields of an 'add object' form using GET variables (e.g. /admin/app/model/add?title=lol sets the 'Title' field to 'lol').

但是,我希望能够按照 /admin/app/model/add?key=18 的方式做一些事情,并从另一个模型的实例中为我的字段加载默认数据.理想情况下,我还希望能够对填充表单的值进行一些处理.我该怎么做?

However, I want to be able to do something along the lines of /admin/app/model/add?key=18 and load default data for my fields from an instance of another model. Ideally, I'd also like to be able to do some processing on the values that I populate the form with. How do I do this?

推荐答案

我设法弄明白了.幸运的是,Django 允许您替换 requestGET 字典(它用于预填充管理表单).以下对我有用:

I managed to figure it out. Thankfully, Django allows you to replace a request's GET dict (which it uses to pre-populate the admin form). The following worked for me:

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

    def add_view(self, request, form_url='', extra_context=None):
        source_id = request.GET.get('source', None)
        if source_id is not 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"... 

[" + source.url + "]",
            })
            request.GET = g

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

这样,我从 URL 参数获取 source 对象,对它们做我想做的事,然后预填充表单.

This way, I obtain the source object from a URL parameter, do what I want with them, and pre-populate the form.

这篇关于Django admin:如何从 GET 变量中填充新对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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