0

This is my code :

<form method="post" enctype="multipart/form-data">{% csrf_token %}

<input type="file" name="myfile">
<button type="submit">Upload</button>
</form>

{% if uploaded_file_url %}
<p>File uploaded at: <a href="{{ uploaded_file_url }}">{{ uploaded_file_url }}</a></p>
{% endif %}

How do I add a file and save it in media directory of application in Django project?

5
  • are u planning to save this file into model?
    – rrmerugu
    Commented Apr 10, 2017 at 10:11
  • i am trying to save a file in media directory of application in django
    – zinc
    Commented Apr 10, 2017 at 10:13
  • ok. but in your scenario do you push the file to database along with uploading it to media/ folder ? or you just need to save it to media/ folder without pushing to database ?
    – rrmerugu
    Commented Apr 10, 2017 at 10:15
  • i just want to upload a text file in the server from a local machine using django framework..I have written a template which has the file upload option on the userinterface..but i am not able to upload a file
    – zinc
    Commented Apr 10, 2017 at 10:17
  • pushing file in database along wiht media/folder or just saving in mdeia/.both are fine..i just need to be able to upload a file..i have read the documetn but not of use
    – zinc
    Commented Apr 10, 2017 at 10:19

2 Answers 2

3

view.py from https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html should work for you !

def simple_upload(request):
    if request.method == 'POST' and request.FILES['myfile']:
        myfile = request.FILES['myfile']
        fs = FileSystemStorage()
        filename = fs.save(myfile.name, myfile) # saves the file to `media` folder
        uploaded_file_url = fs.url(filename) # gets the url
        return render(request, 'core/simple_upload.html', {
            'uploaded_file_url': uploaded_file_url
        })
    return render(request, 'core/simple_upload.html')
3
  • i have used the view and simple_upload.html from the link..but not working
    – zinc
    Commented Apr 10, 2017 at 10:39
  • Did you add these in settings MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
    – rrmerugu
    Commented Apr 10, 2017 at 10:41
  • getting multivlaue error in request.files['myfile']
    – zinc
    Commented Apr 11, 2017 at 7:14
2

File Uploads are covered in the Django Documentation.

There are slight differences depending on if you're trying to upload a file to a Model that got a FileField or ImageField, or if you just simply want to upload a file to your server that does not belong to any model using the Form class.

Please notice, Django have a Form class (Docs) that help you generate forms and handle the POST request with validation and so on. Use this class instead of writing your own HTML code.

Upload File Without Model (Docs)

# forms.py
from django import forms

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

# views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import UploadFileForm

def handle_uploaded_file(f):
    with open('some/file/name.txt', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

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})

Upload File With Model (Docs)

# views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import ModelFormWithFileField

def upload_file(request):
    if request.method == 'POST':
        form = ModelFormWithFileField(request.POST, request.FILES)
        if form.is_valid():
            # file is saved
            form.save()
            return HttpResponseRedirect('/success/url/')
    else:
        form = ModelFormWithFileField()
    return render(request, 'upload.html', {'form': form})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.