How to Upload Files With Django (With Example)

How to Upload Files With Django (With Example)

Django is a high-level Python web infrastructure that allows you to quickly create secure and supported websites. Built by experienced developers, Django takes care of many web development issues, so you can concentrate on writing your application without having to reinvent the wheel. It is a free and open source, has a thriving and active community, excellent documentation and many options for free and paid support.

Django follows the philosophy of “Batteries in the kit” and provides almost everything that developers may want to do “out of the box.” Since everything you need is part of a single “product”, it all works without problems, follows consistent design principles, is an extensible and up-to-date documentation.

If you have everything you need to create a web application, and you want to add images and other files, this article will show you how to do this.

Step 1

We need to think about where your downloaded file will be stored. Since we have already served static files css and js, we can put our resources in the same folder.

Create a new folder in the static folder called «Media». Our files will be stored here.

As usual, we must hit our three main modules: models.py, views.py, urls.py.

Now let’s continue and create a model for this.

Step 2

The Django model comes with a special ImageField. This field is a special type of FileField, which is specialized for image processing. Add an image to the Posts api field. Because this field is required, we specified the default image. Perhaps, you may need to download this image for it to work. For now it’s enough. Don’t forget to transfer your model. Let’s now let Django know how to handle our media.

Step 3

Django calls static files that are downloaded to it by Media. Add the following lines to your settings.py module.

Quit simply, you noticed that we point the folder in a static folder named «Media», which will contain our files. We also provide a Django URL for the same ie media/.

Step 4

Looking at our file views.py, we see that there is nothing to change, the viewset will continue to remain as it is. But we will need to change serialiezer.py, which provides our data.

Now we just added the image field to the serializer.

Step 5

Finally, we need to provide a route to the images, this is accomplished by adding a route to urls.py

Pay attention to the following points:

We import the necessary information from the settings module (line 21, 22)

We add media URLs to ensure that Django can serve it (line 31)

Let’s try to check whether everything works.

Step 6

When you go to the endpoint /posts, you notice a new field.

Igor Grigorenko

Add comment

Subscribe