Search code examples
pythondjangodjango-2.2django-uploads

Upload Image in the wrong directory in django ImageField


When I upload a photo, the photo is loaded successfully, but the photo is placed in the wrong directory.

Instead of placing the image on the path to 'media/posts-pics/' - as I have outlined in my Post model - it is placed on the 'media' path.

These are my files:

models.py

class Post(models.Model): 
    index_pic = models.ImageField(upload_to='posts-pics/')

Project.urls.py

if settings.DEBUG: 
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 

views.py

def add_post(request):
    if request.method == "POST":
        form = AddPostForm(request.POST, request.FILES)
        if form.is_valid():
            new_post = form.save(commit=False)
            new_post.index_pic = form.cleaned_data['index_pic']
            new_post.save()

            return redirect('view_post')

    else:
        form = AddPostForm()
    template = 'post/add_edit_post.html'
    context = {'form': form}
    return render(request, template, context)


def edit_post(request, slug):
    post = get_object_or_404(Post, slug=slug)

    if request.method == "POST":
        form = AddPostForm(request.POST, request.FILES, instance=post)
        if form.is_valid():
            Post.objects.filter(id=post.id).update(title=request.POST['title'],
                                                   index_pic=form.cleaned_data['index_pic'],
                                                   )

            return redirect('view_post')
    else:

        form = AddPostForm(instance=post)
    template = 'post/add_edit_post.html'
    context = {'form': form}
    return render(request, template, context)

I used exactly the same code for add_post, and the photo was in its place, but I got into trouble in edit_post. what's wrong ?

Notice:

Technically I can delete 'media/post-pics' but this is done with a special purpose and the purpose is: Each app have its folder for saving images.


Solution

  • The problem is that you're no using your ModelForm the right way.

    In the edit_post view, you want to replace this:

    Post.objects.filter(id=post.id).update(
        title=request.POST['title'],                                                   
        index_pic=form.cleaned_data['index_pic'],
        )
    

    with a plain simple:

     form.save()
    

    which will take care of the updating the post passed as form.instance (using sanitized data, which is not the case with your current code)

    FWIW, in your add_post view, you also want to replace this

            new_post = form.save(commit=False)
            new_post.index_pic = form.cleaned_data['index_pic']
            new_post.save()
    

    with a plain simple:

            new_post = form.save()
    

    Once again, the whole point of ModelForms is that they know how to create and update model instances.