如何使用 TextInput 小部件获取 Django 外键以显示名称而不是 id?

Sin*_*dex 5 django django-forms

我有以下(本例简化)Django 模型:

class Ingredient(models.Model):
    name = models.CharField(max_length=100)

    def __unicode__(self):
        return self.name

class RecipeIngredient(models.Model):
    quantity = models.DecimalField(max_digits=5, decimal_places=3)
    unit_of_measure = models.ForeignKey(UnitOfMeasure)
    ingredient = models.ForeignKey(Ingredient)
    comment = models.CharField(max_length = 40, blank=True)

    def __unicode__(self):
        return self.id
Run Code Online (Sandbox Code Playgroud)

我有以下表格:

class RecipeIngredientForm(ModelForm):

    class Meta:
        model = RecipeIngredient

    def __init__(self, *args, **kwargs):
        super(RecipeIngredientForm, self).__init__(*args, **kwargs)
        self.fields['quantity'].widget = forms.TextInput(attrs={'size':'6'})
        self.fields['ingredient'].widget = forms.TextInput(attrs={'size':'30'})
        self.fields['comment'].widget = forms.TextInput(attrs={'size':'38'})
Run Code Online (Sandbox Code Playgroud)

当我查看表单时,成分按其 id 值显示,而不是按名称显示。如何显示名称而不是 ID?

更新

一个解决方案(仍然欢迎更优雅的想法)是将 TextInput 小部件子类化并使用该值来获取成分名称:

class IngredientInput(forms.TextInput):
    def render(self, name, value, attrs=None):
        new=Ingredient.objects.get(pk=value).name
        value=new
        if value is None:
            value = ''
        final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
        if value != '':
            # Only add the 'value' attribute if a value is non-empty.
            final_attrs['value'] = force_unicode(self._format_value(value))
        return mark_safe(u'<input%s />' % flatatt(final_attrs))
Run Code Online (Sandbox Code Playgroud)

ale*_*lex -1

IT 显示 id 因为你这么说:

class RecipeIngredient(models.Model):
    def __unicode__(self):
        return self.id
Run Code Online (Sandbox Code Playgroud)

编辑:

...而且,因为您使用 TextInput

self.fields['ingredient'].widget = forms.TextInput(attrs={'size':'30'})
Run Code Online (Sandbox Code Playgroud)

我想你需要这个: https://docs.djangoproject.com/en/1.3/ref/forms/fields/#modelchoicefield