Only Django request.body contains data (not request.POST)
I am using forms in Django and trying to get the get the data back using request.POST
, but this returns an empty dictionary for me: <QueryDict: {}>
. When using request.body
, however, I get the raw data back. How can I get the data from request.POST
as well, because I do not want to work with raw data. The console output of the print statements are put in comments next to them.
forms.py
class NameForm(forms.Form):
first_name = forms.CharField(label='First name:', max_length=100)
last_name = forms.CharField(label='Last name:')
views.py
@csrf_exempt
def blank(request):
form = NameForm()
print(f"request.body: {request.body}") # request.body: b'first_name=Adam&last_name=Smith'
print(f"request.POST: {request.POST}") # request.POST: <QueryDict: {}>
return render(request, 'blank.html', {'form': form})
blank.html
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<form action="" method="post">
{{ form }}
<input type="submit" value="Submit">
</form>
</body>
</html>
Retrieve data from django forms
form = NameForm(request.POST or None)
if form.is_valid():
first_name= form.cleaned_data.get("first_name")
last_name= form.cleaned_data.get("last_name")