urcm
urcm

Reputation: 2284

Django ManyToManyField Error when saving in admin?

What is wrong with my code?

class Group(ImageModel):
     title = models.CharField(verbose_name = "Title", max_length=7)
     photos = models.ManyToManyField('Photo', related_name='+', 
                                             verbose_name=_('Photo'),
                                             null=True, blank=True)

    .....


     pid = Photo.objects.get(image = str_path)

     gid= Group.objects.get(id = self.id)       

     self.save_photos(gid, pid)

    ....


    def save_photos(self, gid, pid):
       group_photo = GroupPhotos(groupupload=gid.id,
                                        photo=pid.id
                                        )
       group_photo.save()

and my GroupPhotos models is:

class GroupPhotos(models.Model):
    groupupload = models.ForeignKey('Group')
    photo = models.ForeignKey('Photo')
    class Meta:
        db_table = u'group_photos'

when i want to save it from admin panel i am getting value error sth like this:

Cannot assign "38": "GroupPhotos.groupupload" must be a "Group" instance.

with group_photo = GroupPhotos(groupupload=gid, photo=pid) defination it is working but there is no any changes in GroupPhotos table(group_photos). printing this print pid.id,' >>> ',gid.id i am getting true relation...

UPDATE:

I have been working since morning, but no progress... i have also tried this but nothing changed:

pid = Photo.objects.get(image = str_path)

ger = Group.objects.get(id = self.id)
        ger.title = self.title       
        ger.save()

        ger.photos.add(pid)

Upvotes: 2

Views: 388

Answers (2)

urcm
urcm

Reputation: 2284

i have solved my problem with adding through option to my manytomanyfield:

photos = models.ManyToManyField('Photo', related_name='+', 
                                     verbose_name=_('Photo'),
                                     null=True, blank=True, through=GroupPhotos)

some info about ManyToManyField.through here:

Django will automatically generate a table to manage many-to-many relationships. However, if you want to manually specify the intermediary table, you can use the through option to specify the Django model that represents the intermediate table that you want to use.

The most common use for this option is when you want to associate extra data with a many-to-many relationship.

Upvotes: 0

Simeon Visser
Simeon Visser

Reputation: 122496

The error is here:

group_photo = GroupPhotos(groupupload=gid.id, photo=pid.id)

The arguments to groupupload and photo should be instances of Group and Photo respectively. Try the following:

group_photo = GroupPhotos(groupupload=gid, photo=pid)

In other words, when creating an object you need to pass arguments of the expected type and not an integer (which may be the primary key key of the desired object but it also might not, which is why you need to pass an object of the correct type).

Upvotes: 4

Related Questions