Open In App

Django - How to Create a File and Save It to a Model's FileField?

Last Updated : 27 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Django is a very powerful web framework; the biggest part of its simplification for building web applications is its built-in feature of handling file uploads with FileField. Images, documents, or any other file types, Django's FileField makes uploading files through our models easy. In this article, we will learn how to create a file and save it in the FileField of a model so we can run our Django application both smoothly and efficiently.

Saving a file in Model Instance

Using FileField for File Uploads

FileField in Django is a particular model field explicitly dealing with file uploads. It allows one to associate files with database records, which comes in very handy for storing user-uploaded files like profile pictures or documents. Once a file has been uploaded via a form, Django takes care of the behind-the-scenes file storage and retrieval, associating those files with the Model Instances to which they belong.

To use FileField, we need to define it in our model.

Example: In the above example file is a FileField that will store uploaded files in the uploads/ directory in the MEDIA_ROOT directory.

Python
from django.db import models

class MyModel(models.Model):
    name = models.CharField(max_length=100)
    file = models.FileField(upload_to='uploads/')

Saving Files to the Model

After defining FileField in your model, we need to provide a way to upload the file. In case using Django's built-in forms or the admin interface, it handles the save procedure for us. If we want or need more control, we can handle file uploads manually by dealing with the FileField directly.

We can save a file to the FileField either by uploading it via a form, or programmatically in our view.

Example

In the example, the save_file_to_model function opens a file from the given file_path and saves it in the file field of the model instance passed. Django takes care of underlying file system operations, storing the file at a specified location.

Python
from django.core.files import File

def save_file_to_model(instance, file_path):
    with open(file_path, 'rb') as f:
        instance.file.save('filename.ext', File(f), save=True)

Code Example

As an example, let's put it all together in one view to demonstrate the process of creating a file, uploading the file, and saving it to the `FileField` of a model.

Project SetUp:

python -m venv venv
venv/Scripts/activate
pip install django
django-admin startproject myproject
django-admin startapp myapp

Don't forget to add myapp to the INSTALLED_APPS in the myproject/settings.py file

Step 1 - Create a Model with a FileField

models.py: Open app/models.py and define a model with a FileField

Python
from django.db import models

class Document(models.Model):
    name = models.CharField(max_length=100)
    file = models.FileField(upload_to='documents/')

Apply the Model Changes:

To apply this model to our database, we'll need to create and apply migrations:

python manage.py makemigrations
python manage.py migrate
ss2
Apply the Model Changes

Step 2: Create a Form to Upload Files

Create a Form: Open myapp/forms.py and create a form:

Python
from django import forms
from .models import Document

class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = ['name', 'file']

Step 3: Create a View to Handle the Form

Define the View:

Open myapp/views.py and define a view:

Python
from django.shortcuts import render
from .forms import DocumentForm

def upload_file(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return render(request,
                        'myapp/upload_success.html',
                        {'document':document}
                    )
              			
    else:
        form = DocumentForm()
    return render(request, 'myapp/upload.html', {'form': form})

Step 4: Create Templates

Create a Template Directory:

Create a directory templates inside the myapp folder, and within it create another directory with the same name as the app name and two files: upload.html and upload_success.html.

upload.html:

HTML
<h2>Upload a File</h2>
<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Upload</button>
</form>
Note: enctype="multipart/form-data" with this attribute, the browser sends the image/files data to the server.

3. upload_success.html:

HTML
<h2>Upload Successful!</h2>
<p>Your file has been uploaded.</p>
<p>File:  <a href={{document.file.url}}>document.file</a> <p>

Also, add make a little change in the settings.py file: add 'template' to the DIRS in the TEMPLATE setting.

Python
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'], #update
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Step 5: Configure URLs

Update myapp/urls.py:

Create a urls.py file inside your myapp folder:

Python
from django.urls import path
from . import views

urlpatterns = [
    path('upload/', views.upload_file, name='upload_file'),
]

Include the App URLs in the Project

Open myproject/urls.py and include the app's URLs:

Python
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('myapp/', include('myapp.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


Also, django to serve static and media files, we need to update few settings and configure URLS.

settings.py

Python
# ...

STATIC_URL = 'static/'
STATIC_ROOT = 'staticfiles'

MEDIA_ROOT = '/media/'
MEDIA_URL = 'media/'

# ...

myproject/urls.py



Test the File Upload

Run the server:

python manage.py runserver

Visit http://127.0.0.1:8000/myapp/upload/ and upload a file:

Conclusion

File uploading in Django is most easily accomplished using the FileField. The robust system in Django would make the whole saving of images, documents, or indeed anything else very easy. We can efficiently handle file uploads in our web application by defining a FileField in our model and then using Django's built-in tools for saving a created file to a model's FileField.


Next Article
Article Tags :
Practice Tags :

Similar Reads