9

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.

here is my code:

models.py

from django.db import models


class Document(models.Model):
    docfile = models.FileField(upload_to='documents/%Y/%m/%d')

forms.py

from django import forms

class DocumentForm(forms.Form):
    docfile = forms.FileField(
        label='Select a file',
    )

views.py

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')

app\urls.py

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)

project\urls.py

from django.conf.urls import patterns, include, url

urlpatterns = patterns('upload.views',
    url(r'^$', 'list', name='list'),
    url(r'^list/$', 'list', name='list'),)
6
  • There are libraries out there - like this one - that provide a database storage backend. Commented Jul 28, 2016 at 6:46
  • @solarissmoke i have seen this github page but how do i use it ? Commented Jul 28, 2016 at 6:48
  • Do not save files in the database. Use the filesystem for that. Commented Jul 28, 2016 at 6:50
  • 3
    @mirosval i have to do it. it does not matter whether i want to do it or not. Commented Jul 28, 2016 at 7:09
  • @superconductor read the documentation? Commented Jul 28, 2016 at 7:24

1 Answer 1

17

Django provides BinaryField that lets you store any binary data, including file contents.

Please do note that the documentation also says:

Although you might think about storing files in the database, consider that it is bad design in 99% of the cases. This field is not a replacement for proper static files handling.

If you'd rather not store the files on your web server's file system, you can explore other options such as Amazon S3 or just an FTP server. Have a look at the django-storages library, it provides a nice bunch of options.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you soo much now i am able to upload files from admin page to database, but can u help me with how to view them and also download them
It would be interesting to understand the advice about avoiding storing files in the database.
You can't serve directly from the database, and both your DB and your application server often have more exciting responsibilities than pushing payloads around. Also I imagine it's convenient to have separation for backups - you might want to have point-in-time recovery for your DB but having same level for files could possibly be unnecessary overhead. OTOH, external file storage can handle backups on its own, serve files directly (with or without auth) and make use of CDN for extra efficiency.
I think noone thinks about strong/serving static files from DB (like JS, CSS which are needed for the visitors of the website). Usually it's the question about upload (zip files, images, attachments). And I heard that for these purposes database works perfectly until quite big high load (100s of GB per day). So for most of the proejcts storing in DB should be perfectly fine

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.