2

I have a simple view which receives files form users. I've tested it with my browser and it works okay.

On the other hand, I have a python and tested it against requestb.in and I can see the multipart/form-data and a http response code 200. So, both my view in receiving and storing files and the script in uploading multipart data work fine.

My problem being: When I use my script to upload a file to the view, even though I get http status code 200, I see no files being stored on the disk while in case of using the browser I do. What would be the problem you think? Here are my model, view and script:

models.py:

class FileUploads(models.Model):
    uploads = models.FileField()

forms.py:

from django import forms
from .models import FileUploads

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = FileUploads
        fields = ['uploads']

views.py:

@csrf_exempt
def upper(request):
    form = UserProfileForm(request.POST or None, request.FILES or None)
    context = {'title': 'welcome', 'form': form}
    if form.is_valid():
        form.save()
        context = {'form': form, 'title': 'thanks'}'
    return render(request, 'upform.html', context)

Python script up.py:

import requests
f = open('C:\\Users\\Amir\\Desktop\\snow.jpg', 'rb')
urls='http://127.0.0.1:8000/upper'
r=requests.post(urls, files= {'a':f})
print(r.status_code)
6
  • 1
    shouldn't it be files= {'uploads':f} ? Commented Nov 29, 2015 at 19:10
  • @Anentropic Ohhh my god, Thank you, I spent almost 5 hours today to figure out the problem. Yes that was the problem. Thank you again. Commented Nov 29, 2015 at 19:27
  • @Anentropic BTW, How can I provide my script with csrt protection, if it is included inside a view, would it suffice to add csrf_protect decorator? Commented Nov 29, 2015 at 21:40
  • Django has csrf enabled by default, so just remove the @csrf_exempt decorator from the view Commented Nov 29, 2015 at 21:49
  • @Anentropic You've been dramatically helpful, thanks; I thought since I am posting the file out side a form with no csrf tag it might not work. Commented Nov 30, 2015 at 21:29

1 Answer 1

2

It should be:

import requests
f = open('C:\\Users\\Amir\\Desktop\\snow.jpg', 'rb')
urls='http://127.0.0.1:8000/upper'
r=requests.post(urls, files= {'uploads':f})
print(r.status_code)

...the name of the file in the dict passed to requests.post needs to match the field name in the Django form :)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.