最佳答案
我是新来的姜戈,没有发现任何关于这个问题的参考。当我在 Django 模型(models.py
)中使用多对多字段时,我得到了这个错误。我想问题在于从表单(forms.py
)分配 m2m 视场(views.py
)。
如何分配 m2m 视场?
(Django version 2.0
,python - 3.5
)
Models.py
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("/")
表格 py
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"]