Django - not able to upload files/images correctly
I am building a Django application (run in local) and I am having headaches about uploading files/pictures. I have read tons of questions/answers everywhere as well as followed the official doc, but somehow I still have problems.
In models.py, I have the following:
class Documents(models.Model):
hkid = models.ImageField("HKID", upload_to='images/', null=False)
Corresponding view in views.py:
class ApplicationUploadView(LoginRequiredMixin, CreateView):
model = Documents
template_name = "home/application.html"
fields = '__all__'
success_url = reverse_lazy('completion')
def form_valid(self, form):
print("form is valid")
//other stuff..
return super().form_valid(form)
In settings.py, I have added (as explained in the docs):
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
And finally, I added this at the end of my urls.py:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
When I run the application, everything works fine - I uploade the picture in the form, and the "form is valid" is also printed on the screen. However, no picture is uploaded at all inside media/ or media/images folder.
However, if I remove the two MEDIA_ROOT and MEDIA_URL lines in settings.py and I remove the "urlpatterns +=" line in urls.py, the picture instead is correctly uploaded, but in a 'images' folder (not inside media, though). However, if I try to open the picture from the admin panel, which has link: http://127.0.0.1:8000/images/hk-id-card-sample.jpg It just gives tells it doesn't exist (but I can see the picture is correctly located at /images/hk-id-card-sample.jpg).
Please help me understanding:
- Why the picture is not uploaded if I add /media/?
- Why I cannot access the picture from the admin panel, even though the link to the file is correct?
Thank you!
Make sure your <form> tag has enctype="multipart/form-data" attribute
<form method="post" enctype="multipart/form-data">
{{your_form_ctx}}
</form>