[Fixed]-Django file upload get data and store in database

1👍

Most people would say just store the file paths in the database and have the web server serve the files. Unless you want people to upload something like a spreadsheet, then you should use a spreadsheet plugin to get the contents into lists and dictionaries which you can write out as models.

Heres how to do it the way you requested:

def handle_uploaded_file(upload):
    contents = file.read() # Add .decode('ascii') if Python 3
    my_model = MyModel(some_other_field='something')
    my_model.field = contents
    my_model.save()

class UploadFileForm(forms.Form):
    title = forms.CharField(max_length=50)
    file = forms.FileField()

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
            return HttpResponseRedirect('/success/url/')
    else:
        form = UploadFileForm()
    return render(request, 'upload.html', {'form': form})

Leave a comment