LoginSignup
6
3

More than 5 years have passed since last update.

DjangoのModelFormでForeignKeyフィールド未選択の見た目を変える方法

Last updated at Posted at 2015-09-29

ModelFormを継承したフォームを実装する際に、ForeignKeyのフィールドにwidgetとしてforms.RadioSelectを適用したところ、下図のように未選択のときの項目が「---------」と表示されており、UI的にちょっと変だなと思ったので、それを変更したときの方法です。

※widgetを適用せず、デフォルトのforms.Selectの場合は「---------」でも普通そうですけど。

デフォルトの図

デフォルト

変更後の図

変更後

コード

models.py

# -*-coding: utf-8-*-                                                                                                                                           
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=30)

    def __unicode__(self):
        return self.name

class Article(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author)

forms.py

# -*-coding: utf-8-*-                                                                                                                                           
from django import forms
from django.forms import ModelForm
from .models import Article, Author

class ArticleForm(ModelForm):
    class Meta:
        model = Article
        fields = '__all__'

    author = forms.ModelChoiceField(
        queryset=Author.objects.all(),
        widget=forms.RadioSelect,
        empty_label='該当なし'
    )

説明

forms.ModelChoiceFieldにempty_labelで任意の文字列を渡してやればOKです。

author = forms.ModelChoiceField(
    queryset=Author.objects.all(),
    widget=forms.RadioSelect,
    empty_label='該当なし'
)
6
3
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3