HI,
I want to validate my urls whether they are post or get with caring the proper data.So i want to validate these urls before they call to respective views.So i am willing to write the some kind of middleware between view and urls so that i can keep safe the system.I am not aware how do i pass the data through middleware code to view.In middle ware i will write the unittest code.which will validate the urls if valid then will pass to the respective view other wise happy to say 404 .So can any buddy suggest me how do i handle the case.Or may be their is another alternative best way to do this validation.
Thanks to all.
You should really be checking for request type in your views, and not in a middleware. As I mentioned in the comments above, you can’t tell whether a request is a POST message from the URL alone, let alone determine what POST data it carries.
Checking the request type within a view is very straight-forward — simple check that
request.methodis equal to"GET"or"POST".If you’re doing this often, a short cut would be to create a decorator which does this check for you. For example, the following decorator checks that a GET request was used to call this view, or else return an
HttpResponseBadRequestobject (status code 400):You can then simply prepend your view function with
@require_GETand the check will be done whever the view is called. E.g.You can do the same for POST.
Here’s an example decorator checking for POST request which takes an optional list of fields that must be provided with the POST request.
Use like this:
or:
Update
OK, my bad. I’ve just reinvented wheel.
Django already provides the
@require_GETand@require_POSTdecorators. See django.views.decorators.http.