1

I am building a REST API server that handles POST requests. The content type in the request is "application/x-www-form-urlencoded".In the request body, we are sending "data1" (some string) and "image" ( a file)

Here's the sample inputForm code I have:

from django import forms

class RequestForm(forms.Form):
    data1= forms.CharField(label='data1',max_length=10000)
    image = forms.ImageField()

I then validate the content in the form request:

if request.method == 'POST':
        form = RequestForm(request.POST)
        print("Form content: {0}".format(form))
        if form.is_valid():
            print("Works")
        else:
            print("Issue")

Now, when I send the above mentioned data, I always get an error. It prints "Issue". In addition, the line taht prints form content shows it as an error. Something like:

<ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="data1" maxlength="10000"

One interesting point: if I remove "Content-type" from the request header, it works.

Any inputs on how I can read the form data correctly when we use content type as application/x-www-form-urlencoded.

thanks in advance...

Omi
  • 762
  • 11
  • 30

2 Answers2

0

As per Django Forms documentation:

By default, each Field class assumes the value is required, so if you pass an empty value – either None or the empty string ("") – then clean() will raise a ValidationError exception

You are on the right track, you should send the form as multipart/form-data as per this thread: Thread about form Content types

L.P.
  • 61
  • 6
0

Found the solution. To begin with, I am sending a file in the input. So I should use content type as "multipart-formdata". In addition, I am using Postman to pump in the REST API requests. In the body of the request, I set form-data which automatically sets the headers correctly based on what I am sending in the body. I was trying to override it with my own header which is not right.

When I resent my http POST request with no headers in Postman, it worked. (of course, I did verify the final http request itself and confirmed Postman is setting the header correctly)

Omi
  • 762
  • 11
  • 30