Display correct choice text for Django inline formset with two foreign keys
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 form开发者_StackOverflow中文版set:
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.
The solution is indeed trivial: just define a __unicode__
method on the Ingredient model to return self.title
.
精彩评论