Upload Files

Learn how to use Django to let your users upload files. This uses only what is built into Django to get you started.

resources

profile_image_form.html

{% extends "base.html" %}

{% block content %}
<form action="{% url "profile_image_upload" %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="submit" />
</form>
{% endblock %}
main:forms.py
from django import forms

class ProfileImageForm(forms.Form):
    image = forms.FileField(label='Select a profile Image')
main/models.py
from django.db import models

class ProfileImage(models.Model):
    image = models.FileField(upload_to='profile/%Y/%m/%d')
main/views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views.generic import FormView, DetailView, ListView

from .forms import ProfileImageForm
from .models import ProfileImage

class ProfileImageView(FormView):
    template_name = 'main/profile_image_form.html'
    form_class = ProfileImageForm

    def form_valid(self, form):
        profile_image = ProfileImage(
            image=self.get_form_kwargs().get('files')['image'])
        profile_image.save()
        self.id = profile_image.id

        return HttpResponseRedirect(self.get_success_url())

    def get_success_url(self):
        return reverse('profile_image', kwargs={'pk': self.id})

class ProfileDetailView(DetailView):
    model = ProfileImage
    template_name = 'main/profile_image.html'
    context_object_name = 'image'


class ProfileImageIndexView(ListView):
    model = ProfileImage
    template_name = 'main/profile_image_view.html'
    context_object_name = 'images'
    queryset = ProfileImage.objects.all()
upper/settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
upper/urls.py
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.conf import settings

from main.views import ProfileImageIndexView

from django.contrib import admin
admin.autodiscover()

from main.views import ProfileImageView, ProfileDetailView

urlpatterns = patterns('',
    url(r'^$', ProfileImageIndexView.as_view(), name='home'),

    url(r'^upload/', ProfileImageView.as_view(), name='profile_image_upload'),
    url(
        r'^uploaded/(?P<pk>\d+)/$', ProfileDetailView.as_view(),
        name='profile_image'),

    url(r'^admin/', include(admin.site.urls)),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
comments powered by Disqus