简体   繁体   中英

Django CreateView with a ManyToMany field?

I've been working on something for a few days, I saw some similar posts here, but I am still having trouble getting it!

I will post a small snippet.

I have a Recipe model, with many fields but I will post the one that I am referring to.

    ingredients = models.ManyToManyField('recipes.Ingredient', related_name='in_recipes')

And then I have an Ingredient model of course, with name, description, etc.

I want to be able to have a CreateView where I can add any amount of ingredients to a single recipe.

I got as far as only being able to list the Ingredients already in my database. I was looking for a single Recipe form that includes the Ingredient form and fields.

Any help would be greatly appreciated!

ingredients = models.ManyToManyField(Ingredient, related_name='in_recipes')

Make sure to put the many to many relationship only in ingerdients model OR on Recipes model, , not in both models !

and any snippet about the create view would be recommended to undesrtand the problem more.

You can save the ingredients after saving the recipe.

class RecipeCreateView(CreateView):

    def save_ingredients(self, recipe):
        ingredients_names = self.request.POST.getlist('ingredients_names')
        for name in ingredients_names:
            ....

    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)
        self.save_ingredients(self.object)
        return response    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM