I've created a Django website in which I allow users to upload Image files using Django's ImageField field. Django docs section about this mentions that there is a vulnerability involved in letting users upload files:
Specifically, an HTML file can be uploaded as an image if that file contains a valid PNG header followed by malicious HTML.
And it says that at the framework level there is no way to prevent this potential malicious behavior, and that one of the ways with which this can be prevented is by only allowing certain file extensions in the web-server's config:
... applications may choose to define a whitelist of allowable file extensions for user uploaded files and configure the web server to only serve such files.
However, I'm using PythonAnywhere and I've found out that there is no way to whitelist file extensions at the server level with PythonAnywhere, and I'll have to use Python to do that in my app.
I'm not sure how I would do that. My guess is that I will have to check for the uploaded file's extension in my Create and Update views, perhaps inside the def post
or def form_valid
methods, but I just don't know how.
Here is what my model and views look like:
models.py:
class Item(models.Model):
title = models.CharField(max_length=255)
image = models.ImageField(upload_to='item_images/', blank=True, null=True)
views.py:
class ItemCreateView(LoginRequiredMixin, CreateView):
model = models.Item
fields = ("title", "image")
class ItemUpdateView(LoginRequiredMixin, UpdateView):
model = models.Item
fields = ("title", "image")
I just want to also mention that the functionality of creating, updating and viewing the item with the uploaded images is working fine, and I've set it so that the uploaded images get stored in a folder named media. Also, I'm on a small budget and would like to avoid having a separate domain for storing and retrieving the user uploaded images.