Reputation: 343
I am working on a Django app and I want the users to be able to upload a csv
file to a folder in the server. Appreciate if you could point me to the right direction.
Upvotes: 2
Views: 7728
Reputation: 343
Here is my complete solution
#view.py
def uploadfunc(request):
if request.method=='POST':
form =uploadfileform(request.POST,request.FILES)
if form.is_valid():
form.save()
return render_to_response('upload_successful.html')
else:
form=uploadfileform()
return render(request, 'upload.html',{'form':form})
#models.py
class uploadfolder(models.Model):
""" my application """
File_to_upload = models.FileField(upload_to='')
#forms.py
#uploading file form
class uploadfileform(forms.ModelForm):
class Meta:
model=uploadfolder
fields=('File_to_upload',)
#upload.html
<form method="post" action="{% url 'uploadfunc'%}" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_table }}
<!-- <button type="submit">Upload</button>-->
<input class="btn btn-primary btn-md" role="button" type="submit" name="submit" value="Upload File" >
</form>
#settings.py
MEDIA_ROOT = "/var/www/vmachines/registry/files/"
MEDIA_URL = "files/"
Upvotes: 2
Reputation: 362
Clients can send files via multi-part requests. Following code demonstrates multi part requests using requests
import requests
url = "http://someurl"
files = {"file" : ("somename.txt", open("pathtofile", "rb"))}
requests.post(url, files=files)
This will give you an InMemoryFile in your server, which you can then save to your server using default_storage
and ContentFile
inbuilt in django
def filehandler(request):
incomingfile = request.FILES['file']
default_storage.save("pathtofolder", ContentFile(incomingfile.read()))
Upvotes: 0
Reputation: 13057
You can just use the django FileField
and that lets you upload the file to the specified folder directly through admin panel and same can be done using the form for normal user.
upload = models.FileField(upload_to='uploads/your-folder/')
Upvotes: 3