[Answer]-Django – Creating objects with m2m relationship while saving form

1👍

Edit:

I misread you question sorry. You have a few problems here. The first is this line

[x.strip() for x in photo.tags.split(',')]

photo.tags is actually a ManyToMany here as

photo = super(PhotoUploadForm, self).save(commit=False)

returns an unsaved Photo object. You might actually want to use

tags = [x.strip() for x in self.cleaned_data['tags'].split(',')]

because self.clean_data will contain the data in the form, and the Photo object won’t have the data atatched until after you have called save on it.

You can’t add ManyToMany‘s until you have actually created the object in the database, because behind the scenes a ManyToMany table looks roughly like this:

class Photo_PhotoTag_M2M_table(models.Model):
    photo = models.ForeignKey(Photo)
    phototag = models.ForeignKey(PhotoTag)

In your PhotoUploadForm.save function, the Photo object actually gets created in the database when you do this line photo.save(). So you need to add your manytomany’s after you have created to form.

(https://docs.djangoproject.com/en/1.7/topics/db/examples/many_to_many/#many-to-many-relationships)

👤vishen

0👍

I don’t know how this works with forms but when overriding the save method for models, you can’t access m2m fields directly, you must use the m2m_changed signal.

I bet here the same is happening because the traceback is similar.

👤argaen

Leave a comment