views:

35

answers:

1

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?

A: 

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

Ashok
but the json_data is coming from RecipeIngredient and I cannot use it like that... I cannot figure out a way to use with a formset
iHeartDucks
i tried with your code, looks like everything is working as expected.for any existing instance of RecipeIngredient, json_data is getting populated properly.
Ashok
This question and answer helpedhttp://stackoverflow.com/questions/3535977/can-model-properties-be-displayed-in-a-template
iHeartDucks