[Django]-Django design: storing and retrieving text files

5👍

If you want to be able to search the contents of these files, then storing them in the database isn’t a terrible idea, but otherwise you should probably go for storing them in the filesystem.

In either case you would want to create a model to hold information about the files:

class TextFile(models.Model):
    user = models.ForeignKey(User, related_name='text_files')

    # if storing in database
    content = models.TextField() 

    # if storing in filesystem
    content = models.FileField(storage=FileSystemStorage(location='/path/to/files'))

You can then have file list view for a particular user like this:

@login_required
def file_list(request):
    files = TextFile.objects.filter(request.user)
    return render(request, 'file_list.html', {'files': files})

And a view to serve the files themselves:

@login_required
def servr_file(request, file_id):
    file = get_object_or_404(TextFile, user=request.user, pk=file_id)

    # if storing in database
    return HttpResponse(file.content)

    # if storing in filesystem
    return HttpResponse(file.content.read())

Leave a comment