How to: One image per thing


#1

Hello! I followed the instructions in Intermediate Concepts for “Adding User-Uploaded Images” but got stuck trying to figure out how to restrict the user to a single image upload. I would like my “thing” to have just one image that can be replaced when a new one is added. I tried this on views.py, thinking I could just limit what was displayed on the detail page, but it showed the first image, not the last one uploaded. What is the best way to go about this?

def adventure_detail(request, slug):
    # grab the object
    adventure = Adventure.objects.get(slug=slug)
    social_accounts = adventure.social_accounts.all()
    uploads = adventure.uploads.all()[:1]
    # and pass to the template
    return render(request, 'adventures/adventure_detail.html', {
        'adventure': adventure,
        'social_accounts': social_accounts,
        'uploads': uploads,
})

#2

Hey Angela, great question!

So, I’m going to try to walk through this without using code:

  • Set up the form as normal for uploading an image.
  • In the view for the edit_photos page, you can check how many uploads have occurred, and if more than one has happened, then you can send a variable to the template to hide the new-upload form if there is already something in uploads for that user.
  • And then you can use a modelform to update the currently uploaded image.

So you’ll restrict what’s in the database to just one image per user to start. :) And that way, when you query for all images, you’ll only receive one.

You can strengthen that by changing your query in the view you passed along — instead of [:1], try using first(): https://docs.djangoproject.com/en/dev/ref/models/querysets/#first

I think both of those will get you closer to what you want! Let me know if that helps.

(BTW, this is just one potential solution, there are likely many other ways to do this, but this is what came into my head!)


#3

Thank you!! This helps a lot.


#4

Glad I could help!