自定义/删除 Django 选择框空白选项 [英] Customize/remove Django select box blank option

查看:27
本文介绍了自定义/删除 Django 选择框空白选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Django 1.0.2.我写了一个由模型支持的 ModelForm.这个模型有一个外键,其中空白=假.当 Django 为这个表单生成 HTML 时,它会为外键引用的表中的每一行创建一个带有一个选项的选择框.它还会在列表顶部创建一个没有值并显示为一系列破折号的选项:

I'm using Django 1.0.2. I've written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a select box with one option for each row in the table referenced by the ForeignKey. It also creates an option at the top of the list that has no value and displays as a series of dashes:

<option value="">---------</option>

我想知道的是:

  1. 从选择框中删除此自动生成选项的最简洁方法是什么?
  2. 自定义它以使其显示为最简洁的方法是什么:

  1. What is the cleanest way to remove this auto-generated option from the select box?
  2. What is the cleanest way to customize it so that it shows as:

<option value="">Select Item</option>

在寻找解决方案时,我遇到了 Django ticket 4653 这给我的印象是其他人有同样的问题,Django 的默认行为可能已被修改.这张票已经一年多了,所以我希望可能有一种更简洁的方法来完成这些事情.

In searching for a solution I came across Django ticket 4653 which gave me the impression that others had the same question and that the default behavior of Django may have been modified. This ticket is over a year old so I was hoping there might be a cleaner way to accomplish these things.

感谢您的帮助,

杰夫

我已将 ForeignKey 字段配置为:

I've configured the ForeignKey field as such:

verb = models.ForeignKey(Verb, blank=False, default=get_default_verb)

这确实设置了默认值,因此它不再是空/破折号选项,但不幸的是它似乎没有解决我的任何一个问题.也就是说,空/破折号选项仍然出现在列表中.

This does set the default so that it's no longer the empty/dashes option but unfortunately it doesn't seem to resolve either of my questions. That is, the empty/dashes option still appears in the list.

推荐答案

没有测试过这个,但是基于阅读 Django 的代码 这里这里 我相信它应该可以工作:

Haven't tested this, but based on reading Django's code here and here I believe it should work:

class ThingForm(models.ModelForm):
  class Meta:
    model = Thing

  def __init__(self, *args, **kwargs):
    super(ThingForm, self).__init__(*args, **kwargs)
    self.fields['verb'].empty_label = None

编辑:这是记录,但如果您使用自动生成的 ModelForm,您不一定知道要查找 ModelChoiceField.

EDIT: This is documented, though you wouldn't necessarily know to look for ModelChoiceField if you're working with an auto-generated ModelForm.

编辑:正如 jlpp 在他的回答中指出的那样,这并不完整 - 在更改 empty_label 属性后,您必须将选项重新分配给小部件.由于这有点 hacky,另一个可能更容易理解的选项是覆盖整个 ModelChoiceField:

EDIT: As jlpp notes in his answer, this isn't complete - you have to re-assign the choices to the widgets after changing the empty_label attribute. Since that's a bit hacky, the other option that might be easier to understand is just overriding the entire ModelChoiceField:

class ThingForm(models.ModelForm):
  verb = ModelChoiceField(Verb.objects.all(), empty_label=None)

  class Meta:
    model = Thing

这篇关于自定义/删除 Django 选择框空白选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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