Initial Data for Django Inline Formsets

这一生的挚爱 提交于 2019-12-04 03:41:44

My first suggestion would be to take the simple way out: save the Recipe and RecipeIngredients, then use the resulting Recipe as your instance when making the FormSet. You may want to add a "reviewed" boolean field to your recipes to indicate whether the formsets were then approved by the user.

However, if you don't want to go down that road for whatever reason, you should be able to populate your formsets like this:

We'll assume that you have parsed the text data into recipe ingredients, and have a list of dictionaries like this one:

recipe_ingredients = [
    {
        'ingredient': 2,
        'quantity': 7,
        'unit': 1
    },
    {
        'ingredient': 3,
        'quantity': 5,
        'unit': 2
    },
]

The numbers in the "ingredient" and "unit" fields are the primary key values for the respective ingredients and units of measure objects. I assume you have already formulated some way of matching the text to ingredients in your database, or creating new ones.

You can then do:

RecipeFormset = inlineformset_factory(
    Recipe,
    RecipeIngredient,
    extra=len(recipe_ingredients),
    can_delete=False)
formset = RecipeFormset()

for subform, data in zip(formset.forms, recipe_ingredients):
    subform.initial = data

return render_to_response('recipes/form_recipe.html', {
     'form': form,
     'formset': formset,
     })

This sets the initial property of each form in the formset to a dictionary from your recipe_ingredients list. It seems to work for me in terms of displaying the formset, but I haven't tried saving yet.

I couldn't make Aram Dulyan code works on this

for subform, data in zip(formset.forms, recipe_ingredients):
    subform.initial = data

Apparently something changed on django 1.8 that i can't iterate a cached_property

forms - django.utils.functional.cached_property object at 0x7efda9ef9080

I got this error

zip argument #1 must support iteration

But i still take the dictionary and assign it directly to my formset and it worked, i took the example from here:

https://docs.djangoproject.com/en/dev/topics/forms/formsets/#understanding-the-managementform

from django.forms import formset_factory from myapp.forms import ArticleForm

ArticleFormSet = formset_factory(ArticleForm, can_order=True)
formset = ArticleFormSet(initial=[
    {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
    {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
])

My code on assign formset to template

return self.render_to_response(
self.get_context_data(form=form, inputvalue_numeric_formset=my_formset(initial=formset_dict)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!