title: How to save files to database in django
body: <p>I am trying to upload files using django forms and save those files in the database itself.
  I have been able to save the link of the file in database and save the file itself in a directory which i specified in Media_root.Can you please help me and tell me what can i change in my code so that files are saved in the database.</p>
  
  <p>here is my code:</p>
  
  <h2>models.py</h2>
  
  <pre><code>from django.db import models
  
  
  class Document(models.Model):
      docfile = models.FileField(upload_to='documents/%Y/%m/%d')
  </code></pre>
  
  <h2>forms.py</h2>
  
  <pre><code>from django import forms
  
  class DocumentForm(forms.Form):
      docfile = forms.FileField(
          label='Select a file',
      )
  </code></pre>
  
  <h2>views.py</h2>
  
  <pre><code>from django.shortcuts import render_to_response
  from django.template import RequestContext
  from django.http import HttpResponseRedirect
  from django.core.urlresolvers import reverse
  from .models import Document
  from .forms import DocumentForm
  
  def list(request):
      # Handle file upload
      if request.method == 'POST':
          form = DocumentForm(request.POST, request.FILES)
          if form.is_valid():
              newdoc = Document(docfile = request.FILES['docfile'])
              newdoc.save()
  
              # Redirect to the document list after POST
              return HttpResponseRedirect(reverse('upload.views.list'))
      else:
          form = DocumentForm() # A empty, unbound form
  
      # Load documents for the list page
      documents = Document.objects.all()
  
      # Render list page with the documents and the form
      return render_to_response(
      'list.html',
      {'documents': documents, 'form': form},
      context_instance=RequestContext(request)
      )
  
  def index(request):
      return render_to_response('index.html')
  </code></pre>
  
  <h2>app\urls.py</h2>
  
  <pre><code>from django.conf.urls import patterns, include, url
  from django.conf import settings
  from django.conf.urls.static import static
  from django.views.generic import RedirectView
  from django.contrib import admin
  # admin.autodiscover()
  
  urlpatterns = patterns('',
          (r'^upload/', include('upload.urls')),
          (r'^$', 'upload.views.index'),
          (r'^admin/', include(admin.site.urls)),) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
  </code></pre>
  
  <h2>project\urls.py</h2>
  
  <pre><code>from django.conf.urls import patterns, include, url
  
  urlpatterns = patterns('upload.views',
      url(r'^$', 'list', name='list'),
      url(r'^list/$', 'list', name='list'),)
  </code></pre>