替换默认的表单的ManyToMany小部件 [英] Replacement for the default ManyToMany Widget of Forms

查看:38
本文介绍了替换默认的表单的ManyToMany小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道谁可以替换django管理界面中的ManyToMany小部件:

I know who to replace the ManyToMany Widget in the django admin interface:

class SomeModelAdmin(admin.ModelAdmin):
    filter_horizontal = ('users',)

但是如何替换所有视图中的默认小部件?

But how to replace the default widget in all views?

我想这可以在不更改代码或Django中一行的情况下实现.

I guess this could be implemented without changing one line in my code or in django.

如果我可以用小部件在这张图片中使用Author部分(ManyToMany输入有两个框)之类的东西,那就太好了

It would be great if I could the something like the Author part (two boxes for a ManyToMany input) in this picture with a widget:

我可以使用 ctrl +单击,但是我的用户不能.他们想要一种更简单的方法.

I can use ctrl + click, but my users can't. They want an easier way.

是否可以在不对代码进行太多更改的情况下替换所有选择多个窗口小部件?

Is there a way to replace all select-multiple widgets without many changes in my code?

推荐答案

如果我不明白您的问题,请在评论中进行说明.

If I do not understand your question, please clarify in the comments.

Django表单小部件文档提供了一些预制的工具可以用来指定表单中字段呈现方式的窗口小部件.

The Django Form Widgets Documentation offers several pre-fab widgets that you can use to specify how a field in your form is rendered.

无需修改视图中的代码,只需在适当的表单字段中添加 widget 关键字arg.

Without modifying the code in my views, I can simply add a widget keyword arg to the appropriate form fields.

forms.py(v1)

forms.py (v1)

class TestForm(forms.Form):
    CHOICES = (
    (1, "choice1"),
    (2, "choice2"),
    (3, "choice3"),
    )
    field = forms.ChoiceField(choices=CHOICES)

这将显示为下拉 select :

<select id="id_field" name="field">
  <option value="1">choice1</option>
  <option value="2">choice2</option>
  <option value="3">choice3</option>
</select>

现在将 widget 关键字arg添加到我的字段中:

Now adding the widget keyword arg to my field:

forms.py(v2)

forms.py (v2)

field = forms.ChoiceField(choices=CHOICES, widget=forms.CheckboxSelectMultiple)

这将显示为复选框列表:

This renders as a list of checkboxes:

<ul id="id_field">
<li>
  <label for="id_field_0"><input id="id_field_0" name="field" type="checkbox" value="1" /> choice1</label>
</li>
<li>
  <label for="id_field_1"><input id="id_field_1" name="field" type="checkbox" value="2" /> choice2</label>
</li>
<li>
  <label for="id_field_2"><input id="id_field_2" name="field" type="checkbox" value="3" /> choice3</label>
</li>
</ul>

编辑

还可以添加Django Admin使用的窗口小部件.有关更多信息,请参见 Django多项选择窗口小部件?.只需导入适当的小部件:

Edit

It is also possible to add widgets that are used by Django Admin. See Django multi-select widget? for more information about this. Simply import the appropriate widget:

from django.contrib.admin.widgets import FilteredSelectMultiple

并改用它.请注意,在这种特殊情况下,您还需要包括表单的 media 以获得所需的效果.

and use that instead. Note that in this particular case you will also need to include the form's media to get the desired effect.

这篇关于替换默认的表单的ManyToMany小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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