C
C
cromvwell2020-09-28 13:23:39
Django
cromvwell, 2020-09-28 13:23:39

How to upload a photo to an album?

models:

class Album(models.Model):
    name = models.CharField(max_length=200, default='')
    description = models.TextField(blank=True, max_length=200, default='')


class Photo(models.Model):
    photo = models.ImageField(blank=True, upload_to='gallery', default=None)
    album = models.ForeignKey(Album, on_delete=models.CASCADE)


views:
def view_album(request, pk):
    album = Album.objects.filter(id=pk)
    photos = Photo.objects.filter(album__id=album[0].id)
    form = PhotoForm
    if request.method == 'POST':
        form = PhotoForm(request.POST)
        if form.is_valid():
            photo = form.save(commit=False)
            photo.album = album[0]
            photo.save()
    return render(request, "album.html", context={'form': form, 'photos': photos})


I'm trying (using a form) to upload a photo, but only id and album.id remain in the database, there is no photo itself, because it is not added to the gallery, besides, the photo is the only thing that is contained in POST. What could be wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2020-09-28
@cromvwell

form = PhotoForm(request.POST, request.FILES)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question