禁止直接分配给多对多集的正面。改用emails_for_help.set()

禁止直接分配给多对多集的正面。改用emails_for_help.set(),第1张

禁止直接分配给多对多集的正面。改用emails_for_help.set()

你需要获取User对象,然后将其添加

emails_for_help
字段中。
ManyToManyField
创建实例时,不能向其添加对象。看一下doc。

class Set_user(FormView):    template_name="pkm_templates/set_up_user.html"    form_class = Set_User_Form    success_url = '/thanks/'    def form_valid(self, form):        org = form.cleaned_data.get('organization')        emails = form.cleaned_data.get("share_email_with")        users = User.objects.filter(email__in=emails)        instance = Setupuser.objects.create(organization=org)        for user in users: instance.emails_for_help.add(user)        return redirect("/")

编辑

这样做的另一种方法是使用

.set()

class Set_user(FormView):    template_name="pkm_templates/set_up_user.html"    form_class = Set_User_Form    success_url = '/thanks/'    def form_valid(self, form):        org = form.cleaned_data.get('organization')        emails = form.cleaned_data.get("share_email_with")        users = User.objects.filter(email__in=emails)        instance = Setupuser.objects.create(organization=org)        instance.emails_for_help.set(users)        return redirect("/")

或者,你可以简单地使用

.add()
添加任意数量的对象。

class Set_user(FormView):    template_name="pkm_templates/set_up_user.html"    form_class = Set_User_Form    success_url = '/thanks/'    def form_valid(self, form):        org = form.cleaned_data.get('organization')        emails = form.cleaned_data.get("share_email_with")        users = User.objects.filter(email__in=emails)        instance = Setupuser.objects.create(organization=org)        instance.emails_for_help.add(*users)        return redirect("/")


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4913110.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-12
下一篇 2022-11-12

发表评论

登录后才能评论

评论列表(0条)

保存