File Upload With Forms

Hi Django developers,

How to handle upload file without request input user? Just I want to read the path file from method: upload_file()

views.py file:


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

def handle_uploaded_file(f):
    return r'C:\Users\bahassans\Downloads\Recordings\Recordings\spine.text'

forms.py file:

from django import forms

class UploadFileForm(forms.Form):
    file = forms.FileField()

Hello,

I am not sure if I fully follow what you want to achieve. You want user to submit form but then use file in your project? In that case you can have form without FileField and work with the project file.

But the absolute path will break once you move your project or deploy it on the server.

1 Like

It’s not possible to accept a user’s files through the browser without their input, because that would be a security concern. Any website could read any file on the user’s computer. Users have to select which files to send to your website.

1 Like

I’m a bit confused about which field to use. What I need is just a Field that will hold a file (audio and/or another one for an image) rather than user uploaded files.

To be clear, I just want to have a field which I can point to a file (audio or image) somewhere in my system. What would be the best way to go about doing this?

Which path? The path that the user selected the file to be uploaded from, the path that you’re saving the file to, or the URL path that you will expose to the user in the browser to retrieve that file? (And what do you think you’re going to be able to do with it after you’ve gotten it?)

Assuming that this is effectively a continuation of this - Managing files name - you haven’t really been clear as to exactly what you’re trying to accomplish. And that means providing more detail than just a one-sentence summary of your overall objective.