Summary: In this tutorial, you will learn how to handle file upload using model and form in Django framework.
In Django, you can handle file uploads using a model field and the FileField
or ImageField
field types. Here’s an example:
from django.db import models
class Document(models.Model):
docfile = models.FileField(upload_to='documents/%Y/%m/%d')
This will define a model with a docfile
field that you can use to store and handle uploaded files. The upload_to
parameter specifies the directory where the files will be uploaded to.
To handle the actual file upload, you will need to create a form and a view in your Django app. Here’s an example of how you can do that:
# forms.py
from django import forms
class DocumentForm(forms.Form):
docfile = forms.FileField(
label='Select a file',
help_text='max. 42 megabytes'
)
# views.py
from django.shortcuts import render, redirect
from .forms import DocumentForm
def upload(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
# handle the file upload
return redirect('upload_success')
else:
form = DocumentForm()
return render(request, 'upload.html', {'form': form})
Finally, you will need to create an HTML template for the file upload form. Here’s an example of how you can do that:
<!-- upload.html -->
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Upload">
</form>
This will create an HTML form that can be used to upload files. When the form is submitted, the file will be uploaded to the specified directory and the upload
view will handle the file upload.