Je suis nouveau sur Django et je n’ai trouvé aucune référence à ce problème. Je reçois cette erreur lorsque j’utilise le champ plusieurs-à-plusieurs dans Django ( models.py). J'imagine que le problème concerne le m2m classé dans view (views.py) à partir de formulaire (forms.py). Comment attribuer un champ m2m à la vue.
Django version 2.O 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)
views.py
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("/")
forms.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"]
Vous devez récupérer l'objet User
puis l'ajouter au champ emails_for_help
. Vous ne pouvez pas ajouter d'objet à ManyToManyField
lors de la création d'une instance. Regardez le 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("/")
[~ # ~] éditer [~ # ~]
Une autre façon de faire est d'utiliser .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("/")
Ou vous pouvez simplement utiliser .add()
pour ajouter un nombre arbitraire d'objets.
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("/")