【问题标题】:Adding extra fields not working in my django form添加在我的 django 表单中不起作用的额外字段
【发布时间】:2010-08-20 01:48:22
【问题描述】:

我有一个带有自定义属性的模型

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)

我想我的问题是如何显示来自额外模型字段的数据?

【问题讨论】:

    标签: django django-models django-templates django-forms


    【解决方案1】:

    将额外字段的数据作为初始数据传递给表单

    initial_data = [{'json_data': objRecipe.json_data}]
    recipeIngredients = RecipeIngredientFormSet(initial=initial_data, instance = objRecipe)
    

    如需正确使用初始数据,请参阅using initial data with formset

    【讨论】:

    • 但是 json_data 来自RecipeIngredient,我不能那样使用它......我想不出一种与表单集一起使用的方法
    • 我试过你的代码,看起来一切都按预期工作。对于任何现有的 RecipeIngredient 实例,json_data 都会正确填充。
    猜你喜欢
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    • 2019-04-15
    • 1970-01-01
    • 2019-12-30
    相关资源
    最近更新 更多