Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use initial in a form with multiple objects without getting MultipleObjectsReturned Error

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading