我有一个带有自定义属性的模型
class RecipeIngredient(models.Model):
recipe = models.ForeignKey(Recipe)
ingredient = models.ForeignKey(Ingredient)
serving_size = models.ForeignKey(ServingSize)
quantity = models.IntegerField()
order = models.IntegerField()
created = models.DateTimeField(auto_now_add = True)
updated = models.DateTimeField(auto_now = True)
def _get_json_data(self):
return u'%s %s' % (self.id, self.ingredient.name)
json_data = property(_get_json_data)
我正在尝试在模板中显示属性“json_data”。
我的表格中有这段代码
class RecipeIngredientForm(forms.ModelForm):
json_data = forms.CharField(widget=forms.HiddenInput())
def __init__(self, *args, **kwargs):
super(RecipeIngredientForm, self).__init__(*args, **kwargs)
print('here')
if kwargs.has_key('instance'):
instance = kwargs['instance']
print(instance)
self.initial['json_data'] = instance.json_data
我知道我的属性'json_data'中的数据无效,但我无法在模板中看到此属性的数据。
在我看来,我有这段代码
RecipeIngredientFormSet = inlineformset_factory(models.Recipe, models.RecipeIngredient, form=forms.RecipeIngredientForm, extra=0)
recipe_id = int(id)
objRecipe = models.Recipe.objects.get(id=recipe_id)
recipe = forms.RecipeForm(instance=objRecipe)
recipeIngredients = RecipeIngredientFormSet(instance = objRecipe)
我想我的问题是如何显示额外模型字段中的数据?
答案 0 :(得分:-1)
将额外字段的数据作为初始数据传递给表单
initial_data = [{'json_data': objRecipe.json_data}]
recipeIngredients = RecipeIngredientFormSet(initial=initial_data, instance = objRecipe)
正确使用初始数据请参考using initial data with formset