Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
65 views
in Technique[技术] by (71.8m points)

How to upload file in django

this might be a pretty stupid question. Also I am new to django. But I was trying to create a basic file upload approach with django where user uploads a file and it gets stored into the defined media path (or whatever that it's called) and that the file size, name, and some other attributes that are needed can be stored into the database. So I have the model ready which will help you understand the question better.

class Document(models.Model):
    file_uid = models.CharField(max_length = 16)
    file_name = models.CharField(max_length = 255)
    file_size = models.CharField(max_length = 255)
    file_document = models.FileField(upload_to='uploaded_files/')
    uploaded_on = models.DateTimeField(auto_now_add=True)
    uploaded_by = models.CharField(max_length=16)

Now it's clearly plain that we don't need to create all the fields in the form and that most them can be received from the file itself (like the name, size). for other attrs like uid and uploaded by those also will be added by the backend. So that's where I am stuck. I have searched for 2 days straight and still couldn't find a proper solution.

As of now this is my views.py

def uploadView(request):
    if(request.method == 'POST'):
        form = FileUploadForm(request.POST, request.FILES)
        uploaded_file = request.FILES['uploaded_file']
        file_dict = {
            'file_uid' : get_random_string(length=10),
            'file_name' :uploaded_file.name,
            'file_size' : uploaded_file.size,
            'file_document' : request.FILES['uploaded_file'],
            'uploaded_by' : get_random_string(length=10)
        }
        form = FileUploadForm(data=file_dict)
        if form.is_valid():
            form.save()
            return HttpResponse("You reached here")
        else:
            return HttpResponse("Your form is invalid")

    else:
        form = FileUploadForm(request.POST, request.FILES)
        return render(request, 'function/upload.html', {
            'form':form
        })

I don't know if this is correct but as of know the form.isvalid() is false.

here's my forms.py

class FileUploadForm(forms.ModelForm):
    file_document = forms.FileField(widget=forms.FileInput(attrs={'name':'uploaded_file'}))

    class Meta:
        model = Document
        fields = ('file_uid', 'file_name', 'file_size', 'file_document', 'uploaded_by')

and my upload page section looks like this

<body>
    <h1>Upload a file</h1>
    <form action="" method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        <input type="file" name="uploaded_file">
        <button type="submit">Upload</button>
    </form>
</body>

If you can mercifully guide me into a proper way of doing this i'll be really gratefull.

question from:https://stackoverflow.com/questions/65869943/how-to-upload-file-in-django

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Before solution, Here are few issues i found in your code

  1. Major issue is how you tried to update the name of your file_document input, it doesn't work this way. confirm this by inspecting in devtools. Checkout my answer here to update name attribute of django input form field. Without updating this, you are not getting file from form.

  2. Not issues just something i would like to point out

def uploadView(request):
    if(request.method == 'POST'):
        form = FileUploadForm(request.POST, request.FILES)
        # your code in between, here the above form is never used and the overridden by the form in next line so why assigning it
        form = FileUploadForm(data=file_dict)
        # your form.is_valid() code start here

    else:
        form = FileUploadForm(request.POST, request.FILES)
        # This block will only run for GET request, why using request.POST, request.FILES
        return render(request, 'function/upload.html', {
            'form':form
        })

Here is how i got your code working

update FileUploadForm like this

class FileUploadForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = ('file_uid', 'file_name', 'file_size', 'file_document', 'uploaded_by')

    # below code is only used to change the name of file_document to uploaded_file
    custom_names = {'file_document': 'uploaded_file'}
    def add_prefix(self, field_name):
        field_name = self.custom_names.get(field_name, field_name)
        return super(FileUploadForm, self).add_prefix(field_name)

use form in html like this

<form method="POST" action="" enctype="multipart/form-data">
    {% csrf_token %}
    {{form.file_document}}
    <input type="submit" value="send"/>
</form>

Update view as

def uploadView(request):
    if(request.method == 'POST'):
        uploaded_file = request.FILES['uploaded_file']
        file_dict = {
            'file_uid' : 'test1',
            'file_name' :uploaded_file.name,
            'file_size' : uploaded_file.size,
            'uploaded_by' : 'hemant'
        }
        form = FileUploadForm(file_dict, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponse("You reached here")
        else:
            return HttpResponse("Your form is invalid")

    else:
        form = FileUploadForm()
        return render(request, 'function/upload.html', {
            'form':form
        })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...