[Fixed]-Django: How to save objects with ManytomayField in Form

1πŸ‘

βœ…

I’m guessing that your model should be something like:

class VKGroup(Model):
  vk_url = ManyToManyField(VKURL, ...)
class VKURL(Model):
  url = CharField / or URLField

Then, if you use a view (as mentionned), you simply do like:

url1 = VKURL(url="https://vk.com/south")
url1.save()
url2 = VKURL(url="https://vk.com/graph")
url2.save()
VKGroup = VKgroup(...)
VKGroup.add(url1,url2)

That’s it!

NB. If you deal with a Form, see this, there is a special Form.save_m2m() method when handling form data. Personally I try to avoid this and deal directly in the view.

πŸ‘€bixente57

0πŸ‘

With this code i was able to solve:

        url1 = Vkgroupstomonitor(vk_group_name="https://vk.com/south3")
        url1.save()
        url2 = Vkgroupstomonitor(vk_group_name="https://vk.com/graph3")
        url2.save()
        project = Userproject(name=sys_project_name, description='test description', user=request.user, date_updated=date_saved,
                                  date_until=date_saved)
        project.save()
        project.vk_groups.add(url1,url2)

Also I prefer to rewrite this with for cycle, without saving one by one

Leave a comment