Home > Software design >  How to use initial in a form with multiple objects without getting MultipleObjectsReturned Error
How to use initial in a form with multiple objects without getting MultipleObjectsReturned Error

Time:12-16

Why is form throwing me an exception of MultipleObjectsReturned, when trying to let users edit their profile cover, I have a model for account and i also created a separate model to hold the upload of users profile cover images given that users can have multiple upload of a profile cover images. but somehow i happen to get this error (get() returned more than one AccountCover -- it returned 2!) when upload is more than one cover image.

 cover = get_object_or_404(AccountCover, account=account.id).first()
    if request.user:
        forms = CoverImageForm(request.POST, request.FILES,instance=cover,
                        initial = {
                            'cover_image':cover.cover_image.url,
                        })
        if forms.is_valid():
            data = forms.save(commit=False)
            data.account = cover.account
            data.save()
            
    
    else:
        forms = CoverImageForm(
            initial = {
                'cover_image':cover.cover_image,
            }
        )

Here is my model for cover image .

class AccountCover(models.Model):
    account = models.ForeignKey(Account,on_delete=models.CASCADE)
    cover_image = models.ImageField(upload_to=get_cover_image_path,blank=True, null=True)

Form for the coverimage

class CoverImageForm(forms.ModelForm):
    class Meta:
        model = AccountCover
        fields  = ['cover_image']

CodePudding user response:

I think that get_object_or_404 needs to return only one object. Try instead with:

from django.http import Http404


cover = AccountCover.objects.filter(account=account.id).first()
if not cover:
    raise Http404()

  • Related