Django CreateView with a ManyToMany field?



我已经做了几天了,我在这里看到了一些类似的帖子,但我仍然无法获得它!

我将发布一个小片段。

我有一个食谱模型,有很多字段,但我会发布我所指的那个。

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

然后我当然有一个Ingredient模型,包括名称、描述等。

我希望能够拥有一个CreateView,我可以在其中将任意数量的成分添加到单个食谱中。

我只能列出数据库中已有的成分。我正在寻找一个包含成分表格和字段的单一食谱表格。

任何帮助将不胜感激!

成分=模型。ManyToManyField(成分, related_name='in_recipes'(

确保只在Ingerdients模型中或Rerecies模型上放置多对多关系!,而不是在两个模型中!

并且建议使用有关创建视图的任何片段来进一步解决问题。

保存食谱后,您可以保存成分。

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    

最新更新