When implementing a form that inherits ModelForm, when forms.RadioSelect
is applied as a widget to the ForeignKey field, the item when it is not selected is" --------- "as shown in the figure below. It is displayed and I thought it was a bit strange in terms of UI, so this is the method when I changed it.
forms.Select
without applying the widget," --------- "is normal.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='Not applicable'
)
It is OK if you pass an arbitrary character string to forms.ModelChoiceField
with empty_label.
author = forms.ModelChoiceField(
queryset=Author.objects.all(),
widget=forms.RadioSelect,
empty_label='Not applicable'
)
Recommended Posts