Site icon Filestack Blog

Everything You Need to Know About Django File Upload

The World Wide Web allows us to move massive amounts of data between networked computers. It is fundamentally a data-creating and data-sharing community. Images, movies, and audio files are some typical human-interpretable formats for this data. Knowing everything about Django file upload makes data sharing easier.

Users have become so accustomed to file sharing that it is no longer regarded as unique, but, instead a standard feature. 

In this tutorial, we’ll look at how to upload a file to a Django-based online application using Python.

We’ve all frequented social media sites like Instagram and Facebook. One thing they all have in common is that users can upload photographs and videos to them. We upload our files to a server, where they are then seen by others. That is what social media is all about.

So, how does Django handle file uploads? 

In this guide, we’ll answer this question. Here is what you’ll learn about in this article:

So let’s begin!

You can learn more about uploading, transforming, and delivering your content in the best way possible at Filestack

Django File Upload: How It Works?

Uploading files is just like any other user input. For instance, when you edit your profile image on Facebook, you choose a file from your device, which you transfer to Facebook’s servers. When someone accesses your profile, the server saves the file, which is then uploaded. You can compare the file to static material on your website. 

In Django, there are a variety of techniques to file uploading and processing. So, we can use models or model forms to implement a file upload. However, in this instance, we’ll use model forms. 

Let’s look at how to upload a file in Django now.

Setting Up the Options: How to do it?

You need these parameters before you can use any file upload application. Add these lines underneath the STATIC FILES settings in the project’s settings.py file.

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

MEDIA_URL = 'media/'

Media Root

By default, MEDIA ROOT is an empty string. It accepts a directory’s exact file path. This directory holds all of the files that a Django user uploads.

Media URL

STATIC URL and MEDIA URL work in a similar way. Instead of providing files with an absolute path, Django uses this URL. When Django serves uploaded file media, it automatically updates the URL.

Create a Media Directory

Create a media directory at the project level.

The manage.py file is on the same level as the media directory.

How to Develop an Application That Creates User Profiles?

Now we’ll use Django to create an application that can store a user profile. We will include a profile photo and some basic information in this profile. We’ll also create a form for uploading the image and go through some key concepts for accomplishing the same with Django.

Create a New Application

Run the command to create a new application from your console now.

In the settings.py file, start installing the new application.

> Python manage.py startapp profile_maker

Create Models

Now, copy and paste the following code into the profile maker/models.py file.

from Django.DB import models

class User_Profile(models.Model):

fname = models.CharField(max_length=200)

lname = models.CharField(max_length = 200)

technologies = models.CharField(max_length=500)

email = models.EmailField(default = None)

display_picture = models.FileField()

def __str__(self):

return self.fname

Interpreting the Code

We’ve created a simple user profile model. fname, lname, technologies, email, and display picture are some of the fields. We also defined a  __str__ function. When we mention the object, this function provides the result of fname. The display picture field is the most crucial.

A FileField is a display picture used to store files on the server. A FileField generates a File object with a lot of built-in properties and functions. When a user uploads a file to the FileField, it stores the File object is stored in the database. The file goes to the Media Root. 

The purpose of a File object is to link a file to an object or profile. 

Are you looking for a way to streamline your content uploads? Filestack’s robust infrastructure handles billions of uploads, modifications, and downloads, delivering excellent performance to consumers all over the world.

How to Produce Forms?

In your application, create a new forms.py file. Paste the following code into the profile maker/forms.py file:

from Django import forms

from .models import User_Profile

#DataFlair #File_Upload

class Profile_Form(forms.ModelForm):

class Meta:

model = User_Profile

fields = [

'fname',

'lname',

'technologies',

'email',

'display_picture'

]

Interpreting the Code

We are using Model forms here. These shapes are unique and quite useful.

Model Forms 

The main idea behind model forms is that their structure is derived from models. That’s right, we don’t need to create a form or link it to models. This is something we can achieve directly using model forms.

Forms with models are a subtype of forms. We use the META class when creating a form with the ModelForm class. 

 META requires two qualities:

  1. Model – It takes in the model’s name. For this, we’ll need to import the User Profile model, which specifies the model that will be used to render a form. Use the form object to save user information and store it properly in a database. 
  2. Fields – This list includes the names of the model’s fields. It specifies the form’s data input. We also define the fields from models in this list. 

Import the Models and Forms

Now insert this code into the profile maker/views.py file.

from django.shortcuts import render

from .forms import Profile_Form

from .models import User_Profile

IMAGE_FILE_TYPES = ['png', 'jpg', 'jpeg']

def create_profile(request):

form = Profile_Form()

if request.method == 'POST':

form = Profile_Form(request.POST, request.FILES)

if form.is_valid():

user_pr = form.save(commit=False)

user_pr.display_picture = request.FILES['display_picture']

file_type = user_pr.display_picture.url.split('.')[-1]

file_type = file_type.lower()

if file_type not in IMAGE_FILE_TYPES:

return render(request, 'profile_maker/error.html')

user_pr.save()

return render(request, 'profile_maker/details.html', {'user_pr': user_pr})

context = {"form": form,}

return render(request, 'profile_maker/create.html', context)

The viewpoints are straightforward. In this view file, we’ve imported the models and forms. Then we created a list called IMAGE FILE TYPES. We use it to determine the file type.

Then we define our function.

This function generates a form object and creates a form. Then, to tidy up our form data, we use form validation. The function returns True or False. We can store the information locally if the form has valid information. Then we retrieve the file type the user uploaded.

How to Make a Template?

Make a templates folder once more. Profile maker/templates/profile maker is the directory pattern. 

Don’t forget to create two folders. The templates directory comes first, followed by the profile maker directory within it.

Create a new file called create.html in profile maker/templates/profile maker.

In create.html, paste the following code.

<!DOCTYPE html>

<html>

<head>

<title>Make Profile</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

</head>

<body>

<center>

<div class="jumbotron">

<h1 class="display-4">DataFlair Django File Uploading</h1>

{% block replace %}

<p class="lead">To make a user profile and upload the files fill this form</p>

<hr class="my-4">

<form method="POST" enctype="multipart/form-data">

<!-- Very Important csrf Token -->

{% csrf_token %}

<table>

{{ form.as_table }}

</table>

<input type="submit" class="btn btn-primary btn-lg" name="register">

</div>

</center>

{% endblock %}

</body>

</html>

It’s a straightforward template that renders the form using Bootstrap. The form attribute type is the most significant aspect. This property lets us send our data files.

Even though we have an image file, we have not used an API to retrieve its contents. Now, create a new file in the same directory, called details.html. Fill in the blanks with this code:

{% extends 'profile_maker/create.html' %}

{% block replace %}

<CENTER>

<div class="jumbotron">

<h1 class="display-4">Welcome to DataFlair<br>Hello {{ user_pr.fname }}</h1>

<p class="lead">its an awesome profile picture</p>

<hr class="my-4">

<img src="{{ user_pr.display_picture.url }}" class="image_responsive" height="100px" width="100px">

<p>

{{ user_pr.display_picture.url }}<BR>

You have learned some awesome technologies like {{ user_pr.technologies }}</p>

</div>

</CENTER>

{% endblock %}

The image we just submitted is shown using this template. In the image SRC, we use the user pr. display picture.URL. 

How to Set Up the URLs?

Once you have created all of the files, open the urls.py file in your main directory, and copy and paste the code.

How to Test the Application?

We’re now ready to put our app to the test. In the address bar, type localhost:8000/upload.

You’re done. 

Are You Ready to Explore More in Files Uploads? 

Django can handle files in a variety of ways. This is what makes Django a fantastic framework. It allows us to read files and use machine learning techniques or any other backend procedure.

The method we showed above is one of the ways we can upload and render files in Django. For the most part, the method works well, but you can tweak it to fit your needs.

Filestack can simplify the uploading and storage experience of file uploading. So what are you waiting for? Explore more about one of the best file upload methods!

Exit mobile version