显示带有两个外键的 Django 内联表单集的正确选择文本
我已经成功地使用内联表单集创建了一个配方输入表单,其中包含一个配方表单(只是一个模型表单)和一个 RecipeIngredient 表单集。模型是:
#models.py
class Recipe(models.Model):
title = models.CharField(max_length=255)
description = models.TextField(blank=True)
directions = models.TextField()
class RecipeIngredient(models.Model):
quantity = models.DecimalField(max_digits=5, decimal_places=3)
unit_of_measure = models.CharField(max_length=10, choices=UNIT_CHOICES)
ingredient = models.CharField(max_length=100, choices=INGREDIENT_CHOICES)
recipe = models.ForeignKey(Recipe)
我想将成分更改为以下内容:
ingredient = models.ForeignKey(Ingredient)
其中成分是:
class Ingredient(models.Model):
title = models.CharField(max_length=100)
我保持views.py不变以设置内联表单集:
FormSet = inlineformset_factory(Recipe, RecipeIngredient, extra=1,
can_delete=False)
一切都运行良好......直到我单击成分下拉菜单,除了“什么也没有看到”对每个成分条目重复“成分对象”选择,而不是我正在寻找的标题值。
有什么方法可以保持这种直接的方法并在下拉列表中显示 Ingredient.title 吗?这在保存、显示等方面还会有其他问题吗?
如果做不到这一点,我需要做什么才能使这项工作成功?
谢谢大家。
I have successfully used inline formsets to create a recipe input form that consists of a Recipe form (just a model form) and a RecipeIngredient formset. The models are:
#models.py
class Recipe(models.Model):
title = models.CharField(max_length=255)
description = models.TextField(blank=True)
directions = models.TextField()
class RecipeIngredient(models.Model):
quantity = models.DecimalField(max_digits=5, decimal_places=3)
unit_of_measure = models.CharField(max_length=10, choices=UNIT_CHOICES)
ingredient = models.CharField(max_length=100, choices=INGREDIENT_CHOICES)
recipe = models.ForeignKey(Recipe)
I want to change the ingredient to the following:
ingredient = models.ForeignKey(Ingredient)
Where Ingredient is:
class Ingredient(models.Model):
title = models.CharField(max_length=100)
I left views.py unchanged to set up the inline formset:
FormSet = inlineformset_factory(Recipe, RecipeIngredient, extra=1,
can_delete=False)
And everything worked perfectly ... until I clicked the ingredient drop down and saw nothing but "Ingredient object" choices repeated for every ingredient entry rather than the title value I was looking for.
Is there any way to maintain this straight forward approach and display Ingredient.title in the dropdowns? Will this have any other problems wrt saving, displaying, etc.?
Failing that, what do I need to do to make this work?
Thanks all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决方案确实很简单:只需在 Ingredient 模型上定义一个
__unicode__
方法即可返回self.title
。The solution is indeed trivial: just define a
__unicode__
method on the Ingredient model to returnself.title
.