开发者

Adding extra fields not working in my django form

I have a model with a custom property

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)

I am trying to display the property 'json_data' in my template.

I have this piece of code in my form

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

I know the data in my property 'json_data' is not valid, but I am unable to see the data from this property in my template.

In my views, I have this piece of code

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)

I guess my question is how do I display data from an extra model field?


pass the data of the extra fields as initial data to the form

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

for correct usage of initial data refer using initial data with formset

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜