Cannot Upload Image In Django Using Filefield
Solution 1:
There are many problems with your code:
In your model - use the field for image uplaoding
ImageField
(to useImageField
you need to have installed Pillow):image = models.ImageField(upload_to = 'images/' , null= True, blank= True)
(you will upload the images in a subfolder of the MEDIA_ROOT folder named
images
)Also put the images in the media folder - you have to create one, in the settings.py folder add:
MEDIA_URL = '/media/'MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
To let django serve your media (only for development!) you have to add in your main (from your project directory not from your app folder) urls.py file:
from django.conf import settings from django.conf.urls.static import staticif settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
An example of a simple form to upload an image:
<form action="{% url upload_pic %}" method="post" enctype="multipart/form-data">{% csrf_token %} <input id="id_image"type="file" class="" name="image"> <input type="submit" value="Submit" /> </form>
where
url_upload_pic
is the (function) view which should handle the upload of the image.
Solution 2:
And I think a good thing too.
MEDIA_ROOT and STATIC_ROOT must have different values. Before STATIC_ROOT was introduced, it was common to rely or fallback on MEDIA_ROOT to also serve static files; however, since this can have serious security implications, there is a validation check to prevent it.
https://docs.djangoproject.com/en/1.11/ref/settings/#media-root
What you want to be doing (in development) is to follow this guide: https://docs.djangoproject.com/en/1.11/howto/static-files/#serving-files-uploaded-by-a-user-during-development
During development, you can serve user-uploaded media files from MEDIA_ROOT using the django.views.static.serve() view.
This is not suitable for production use! For some common deployment strategies, see Deploying static files.
For example, if your MEDIA_URL is defined as /media/, you can do this by adding the following snippet to your urls.py:
Basically, you updload the files to a place in MEDIA_ROOT and then tell django to treat them almost like static. But you don't directly upload to static.
Post a Comment for "Cannot Upload Image In Django Using Filefield"