</>
Skip to content
Django lessons (30/43)

Django — File Upload

Model with FileField

class Document(models.Model):
    title = models.CharField(max_length=100)
    file = models.FileField(upload_to='documents/%Y/%m/')
    uploaded_at = models.DateTimeField(auto_now_add=True)

Upload Form

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

View

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

Template

<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Upload</button>
</form>

File Access

# In template
<a href="{{ document.file.url }}">Download</a>
<img src="{{ document.image.url }}" alt="Image">

# In Python
document.file.name   # Filename
document.file.url    # Full URL
document.file.size   # File size

Multiple File Upload

class MultipleFileForm(forms.Form):
    files = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))

Mini Practice

  1. Create a file upload form
  2. Handle file uploads in views
  3. Display uploaded files
  4. Implement multiple file upload

Up Next

Continue with Email — sending emails in Django.

Related Topics

Frequently Asked Questions about File Upload

What is File Upload in Django?

File Upload is a fundamental concept in Django. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn File Upload?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn File Upload.

Why is File Upload important in Django?

File Upload is essential for Django development. Understanding this concept will help you write better code and solve real-world problems more effectively.