我是Django的新手,但未找到有关此问题的任何参考。当我在Django模型(models.py)中使用多对多字段时,出现此错误。我猜问题是在views.pyform(forms.py)的view()中分配m2m字段。
models.py
views.py
forms.py
如何在视图中分配m2m字段?(Django version 2.0,python - 3.5)
Django version 2.0
python - 3.5
class User(AbstractUser): username=models.CharField(max_length=20) email = models.EmailField(_('email address'), unique=True) class Setupuser(models.Model): organization=models.CharField(max_length=200,blank=False,null=True) emails_for_help = models.ManyToManyField(User)
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("emails_for_help") instance = Setupuser(organization=org,emails_for_help=emails) instance.save() return redirect("/")
表格
class Set_User_Form(ModelForm): emails_for_help = forms.ModelMultipleChoiceField( queryset=User.objects.all(), widget=forms.CheckboxSelectMultiple ) class Meta: model = Setupuser fields = ["organization","emails_for_help"]
你需要获取User对象,然后将其添加到emails_for_help字段中。ManyToManyField创建实例时,不能向其添加对象。看一下doc。
emails_for_help
ManyToManyField
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()。
.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()添加任意数量的对象。
.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("/")