python Django - 如何预填充管理表单字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/529890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:18:48  来源:igfitidea点击:

Django - How to prepopulate admin form fields

pythondjangodjango-admindjango-forms

提问by sacabuche

I know that you can prepopulate admin form fields based on other fields. For example, I have a slug field that is automatically populated based on the title field.

我知道您可以根据其他字段预填充管理表单字段。例如,我有一个基于标题字段自动填充的 slug 字段。

However, I would also like to make other automatic prepopulations based on the date. For example, I have an URL field, and I want it to automatically be set to http://example.com/20090209.mp3where 20090209 is YYYYMMDD.

但是,我还想根据日期进行其他自动预填充。例如,我有一个 URL 字段,我希望它自动设置为http://example.com/20090209.mp3,其中 20090209 是 YYYYMMDD。

I would also like to have a text field that automatically starts with something like "Hello my name is author" where author is the current user's name. Of course, I also want the person to be able to edit the field. The point is to just make it so the user can fill out the admin form more easily, and not just to have fields that are completely automatic.

我还想要一个文本字段,它会自动以“你好,我的名字是作者”之类的内容开头,其中作者是当前用户的姓名。当然,我也希望此人能够编辑该字段。重点是让用户可以更轻松地填写管理表单,而不仅仅是拥有完全自动的字段。

回答by sacabuche

I know that you can prepopulate some values via GET, it will be something like this

我知道你可以通过 GET 预先填充一些值,它会是这样的

http://localhost:8000/admin/app/model/add/?model_field=hello

I got some problems with date fields but, maybe this could help you.

我在日期字段方面遇到了一些问题,但是,也许这可以帮助您。

回答by bjunix

I recently used Django's ModelAdmin.get_formmethod for this purpose.

我最近为此使用了 Django 的ModelAdmin.get_form方法。

class MyModelAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        form = super(MyModelAdmin, self).get_form(request, obj, **kwargs)
        form.base_fields['my_field_name'].initial = 'abcd'
        return form

Yout should be careful about side effects as you are manipulating the base_fields directly.

当您直接操作 base_fields 时,您应该注意副作用。

回答by Carl Meyer

Django's built-in prepopulated_fields functionality is hardcoded to slugify, it can't really be used for more general purposes.

Django 的内置 prepopulated_fields 功能被硬编码为 slugify,它不能真正用于更一般的目的。

You'll need to write your own Javascript function to do the prepopulating. The best way to get it included in the admin page is to include it in the inner Media classof a custom Form or Widget. You'll then need to customize your ModelAdmin subclassto use the custom form or widget. Last, you'll need to render some inline Javascript along with each prepopulated field to register the onchange handler and tell it which other field to populate from; I would render this via the custom Widget. To make it nice and declarative you could use a custom ModelAdmin attribute (similar to prepopulated_fields), and override ModelAdmin.formfield_for_dbfield to create the widget and pass in the information about what field it should prepopulate from.

您需要编写自己的 Javascript 函数来进行预填充。将其包含在管理页面中的最佳方法是将其包含在自定义 Form 或Widget内部 Media 类中。然后,您需要自定义ModelAdmin 子类以使用自定义表单或小部件。最后,您需要渲染一些内联 Javascript 以及每个预填充的字段以注册 onchange 处理程序并告诉它要填充的其他字段;我会通过自定义小部件呈现这个。为了使它更好和声明性,您可以使用自定义 ModelAdmin 属性(类似于 prepopulated_fields),并覆盖 ModelAdmin.formfield_for_dbfield 以创建小部件并传入有关它应该从哪个字段预填充的信息。

This kind of admin hacking is almost always possible, but (as you can tell from this convoluted summary) rarely simple, especially if you're making an effort to keep your code nicely encapsulated.

这种管理员黑客攻击几乎总是可能的,但是(从这个令人费解的摘要中可以看出)很少是简单的,特别是如果您正在努力保持代码很好地封装。

回答by Andrea Di Persio

You can override the default django admin field by replacing it with a form field of your choice.

您可以通过将其替换为您选择的表单字段来覆盖默认的 django 管理字段。

Check this : Add custom validation to the admin

检查这个: 向管理员添加自定义验证

回答by anonymous coward

I would also like to have a text field that automatically starts with something like "Hello my name is author".

我还想要一个自动以“你好,我的名字是作者”开头的文本字段。

Check out the docs at: http://docs.djangoproject.com/en/dev/ref/models/fields/#default

查看文档:http: //docs.djangoproject.com/en/dev/ref/models/fields/#default

You could have a CharField() or TextField() in your model, and set this option, which will set the default text. 'default' can also be a callable function.

您可以在模型中使用 CharField() 或 TextField(),并设置此选项,这将设置默认文本。'default' 也可以是一个可调用的函数。

Something like: models.CharField(max_length=250, default="Default Text")

类似于:models.CharField(max_length=250, default="Default Text")

回答by Mr Shark

The slug handling is done with javascript.

slug 处理是用 javascript 完成的。

So you have to overridethe templates in the admin and then populate the fields with javascript. The date thing should be trivial, but I dont know how you should get the logged in users name to the script (not that I have thought very hard but you get the drift :).

因此,您必须覆盖管理中的模板,然后使用 javascript 填充字段。日期的事情应该是微不足道的,但我不知道你应该如何将登录的用户名获取到脚本中(不是我想得很辛苦,但你明白了:)。

回答by Till Kolter

I tried a few of these answers and none of them worked. I simply wanted to prepulate a field with another field from a related model. Taking thisanswer as a starting point, I finally tried to manipulate the model instance object (here obj) directly and it worked for me.

我尝试了其中的一些答案,但都没有奏效。我只是想用相关模型中的另一个字段来准备一个字段。以这个答案为起点,我终于尝试直接操作模型实例对象(这里obj)并且它对我有用。

class MyModelAdmin(models.ModelAdmin):

    def get_form(self, request, obj=None, **kwargs):
        form = super(MyModelAdmin, self).get_form(request, obj, **kwargs)
        if not obj.some_model_field:
            obj.some_model_field = obj.related_model.prepopulating_model_field

        return form