Categories
Python Answers

How to fix Direct assignment to the forward side of a many-to-many set is prohibited. Use emails_for_help.set() instead with Python Django?

Spread the love

Sometimes, we want to fix Direct assignment to the forward side of a many-to-many set is prohibited. Use emails_for_help.set() instead with Python Django.

In this article, we’ll look at how to fix Direct assignment to the forward side of a many-to-many set is prohibited. Use emails_for_help.set() instead with Python Django.

How to fix Direct assignment to the forward side of a many-to-many set is prohibited. Use emails_for_help.set() instead with Python Django?

To fix Direct assignment to the forward side of a many-to-many set is prohibited. Use emails_for_help.set() instead with Python Django, we should add our many to many relations objects after the original object is created.

For instance, we write

class SetUser(FormView):
    template_name="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("/")

to create the user object with

instance = SetupUser.objects.create(organization=org)

And then we add the user into the emails_for_help many to many field by writing

for user in users:
    instance.emails_for_help.add(user)

Conclusion

To fix Direct assignment to the forward side of a many-to-many set is prohibited. Use emails_for_help.set() instead with Python Django, we should add our many to many relations objects after the original object is created.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *