doniyor
doniyor

Reputation: 37886

django - check if form data exists in request

This is a crazy question, I know, but I just want to make sure.

There is this code in Django:

if request.method == 'POST':
     do_something()

It checks if the form was really submitted in POST method. My question is: does it also check if there is a form data in request at all? I mean, I could take the preview page's url and just visit this link without filling form fields. Does this check above detect this case?

If it does not check for form data existence, how can I achieve this? Btw, I am not using Django forms. I am just receiving data in view like this:

data['year'] = request.POST.get('year')

and all validation is happening in frontend with Javascript.

Upvotes: 0

Views: 5231

Answers (3)

doniyor
doniyor

Reputation: 37886

First of all, I encourage you all to go for django-forms. I will also switch to django forms step by step from now on.

but for those who missed something beautiful like django forms like me - this is a quick solution for checking if there is form data at all inside request body.

if len(request.body) > 0: 
  # there is something inside request body
else: 
  # random link visit and no form data at all

here is more about HttpRequest.body

Upvotes: 1

Andrew Gorcester
Andrew Gorcester

Reputation: 19973

That only checks the method, it does not check for form data. There are some uses of the POST method that does not include form data, for instance if all of the information needed to create a resource is in the URL.

If you are using Django's form system, form validation will of course fail to pass if there is no form data.

Upvotes: 1

alecxe
alecxe

Reputation: 473873

Nope, this is just a HTTP Request method check.

In order to check if the form data is there (if form validates), call is_valid() on the Form instance.

Upvotes: 1

Related Questions