Image wont save in database

I want to save an image in the database with a Model and a Modelform, but if I save it there is no media folder or database entry.

class Entry(models.Model):
    picture = models.ImageField(upload_to='file')
def ImageView(request):
        form = ImageForm(request.FILES)
        if request.method == 'POST':
            form = ImageForm(request.POST, request.FILES)
            if form.is_valid():
                form.save()

            return redirect('home:index')
        else:
            
                        
            context= {
                'form': form

                }
        
        return render(request, 'home/image_form.html', context)
class ImageForm(ModelForm):
    class Meta:
        model = Entry
        fields = ['picture']

app_name = 'home'
urlpatterns = [
    path('image/', views.ImageView, name="image"),
]

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

<form action="{% url 'home:image' %}" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button class="button btn btn-dark" type="submit">Done</button>
    <a href="" class="button btn btn-dark">Cancel</a>

</form>
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
  • You’re not handling the case where form.is_valid is False. If there is something wrong in the form being submitted, and there are no errors being generated on the console, you won’t see or know what’s happening.

  • You’re creating an instance of form twice - once before the if request.method condition and once within it. I’d move that first one into the else clause.

  • You’re trying to save the file inside a directory named file inside your media directory. Does that file directory exist?

  • You’re trying to define your MEDIA_ROOT as within your project directory structure. This may work in a test / development environment, but is a phenominally bad idea for any kind of production deployment.

1 Like

In addition to Ken’s comments I believe you need to set the enctype to multipart/form-data to send the actual image in the post. See the MDN docs for more info: HTMLFormElement.enctype - Web APIs | MDN

Good catch - it’s also documented / identified in the second paragraph after the first example here: File Uploads | Django documentation | Django with a little more detail and an example here: The Forms API | Django documentation | Django

thank you so much , i had same problem and its fixed now :slightly_smiling_face: