82

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>

What I'd like to know is:

  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>
    

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.

Thanks for any help,

Jeff

Edit: 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.

4

15 に答える 15

96

これはテストしていませんが、ここここでDjangoのコードを読んだことに基づいて、うまくいくはずだと思います。

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を探す必要があるとは限りません。

編集:jlppが彼の回答で述べているように、これは完全ではありません。empty_label属性を変更した後、ウィジェットに選択肢を再割り当てする必要があります。これは少しハッキーなので、理解しやすい他のオプションは、ModelChoiceField全体をオーバーライドすることです。

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

  class Meta:
    model = Thing
于 2009-04-11T12:40:43.337 に答える
39

ドキュメントから

モデル フィールドに blank=False があり、明示的な既定値が指定されている場合、空白の選択肢は含まれません (代わりに既定値が最初に選択されます)。

デフォルトを設定すればOKです

于 2009-04-11T00:58:57.440 に答える
21

これをモデルで使用できます:

class MyModel(models.Model):
    name = CharField('fieldname', max_length=10, default=None)

デフォルト=なしが答えです:D

注:Django 1.7でこれを試しました

于 2014-07-21T15:22:22.313 に答える
8

django 1.4に関しては、choicesフィールドに「default」値と「blank = False」を設定するだけです

class MyModel(models.Model):
    CHOICES = (
        (0, 'A'), 
        (1, 'B'),
    )
    choice_field = models.IntegerField(choices=CHOICES, blank=False, default=0)
于 2012-07-30T12:50:51.640 に答える
6

あなたは管理者でこれを行うことができます:

formfield_overrides = {
    models.ForeignKey: {'empty_label': None},
}
于 2013-04-27T10:52:25.097 に答える
5

self.fields['xxx'].empty_value = NoneフィールドタイプがプロパティTypedChoiceFieldを持たない場合は機能しません。empty_label

私たちがすべきことは、最初の選択肢を削除することです:

1. BaseForm自動検出を構築したい場合TypedChoiceField

class BaseForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(BaseForm, self).__init__(*args, **kwargs)

        for field_name in self.fields:
            field = self.fields.get(field_name)
            if field and isinstance(field , forms.TypedChoiceField):
                field.choices = field.choices[1:]
            # code to process other Field
            # ....

class AddClientForm(BaseForm):
     pass

2. いくつかのフォームのみを使用できます。

class AddClientForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(AddClientForm, self).__init__(*args, **kwargs)
        self.fields['xxx'].choices = self.fields['xxx'].choices[1:]
于 2015-05-24T09:03:09.010 に答える
5

この問題の完全な議論と解決方法については、こちらを参照してください。

于 2009-09-01T15:29:11.007 に答える