Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save files to database in django

Tags:

python

django

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'),)
like image 940
superconductor Avatar asked Jul 28 '16 06:07

superconductor


People also ask

How does Django save data to database?

Creating objectsTo create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.

What is Save () in Django?

save() , django will save the current object state to record. So if some changes happens between get() and save() by some other process, then those changes will be lost.

How do I serve media files in Django?

Media Files in Development Mode Unfortunately, the Django development server doesn't serve media files by default. Fortunately, there's a very simple workaround: You can add the media root as a static path to the ROOT_URLCONF in your project-level URLs.


1 Answers

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.

like image 114
Kos Avatar answered Sep 30 '22 05:09

Kos