开发者

django - many to many field rendered as dropdown issue

Model:

class ExpertLevel(models.Model):
    level = models.CharField(max_length=100)
    subject = models.ManyToManyField(Subject, blank=True, null=True)

class Expert(models.Model):
    appuser = models.ForeignKey(AppUser , unique=True)
    level = models.ManyToManyField(Expe开发者_开发百科rtLevel, blank=True, null=True)

Form:

class EditExpertForm(ModelForm):
    class Meta:
        model = Expert
        fields = ('level',)
        widgets = {'level': Select()}

Issue: The level field(from Expert model) rendered in template doesn't include blank choice( which should be there for default).

The documentation states that "The blank choice will not be included if the model field has blank=False and an explicit default value (the default value will be initially selected instead).".. while here it is blank=True.

Any reasons??


Further on the same page, you will see that:

If you explicitly instantiate a form field like this, Django assumes that you want to completely define its behavior; therefore, default attributes (such as max_length or required) are not drawn from the corresponding model. If you want to maintain the behavior specified in the model, you must set the relevant arguments explicitly when declaring the form field.

(This is contained in the chapter Overriding the default field types or widgets).

I do agree that the documentation is confusing regarding this matter; one tends to quickly read over these warnings (in other words: I've had the same issue once and had to re-read the documentation quite a few times before actually understanding that the warning applied to your case - changing the widget type - too).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜