I'm using a private view in my Django project for an AJAX request.
def HereIsSomeJSON(request, label):
if not request.method == "POST":
raise PermissionDenied
# Here is the job of my AJAX, basically feeding a JSON
json = {...}
return HttpResponse(json, "application/json")
Using JavaScript, I request for the AJAX with jQuery as so:
function FeedMeWithJSON() {
// Django needs his Cross-Site Request Forgery token to welome POST datas
oPostDatas = {
'csrfmiddlewaretoken': '{{ csrf_token }}'
};
jQuery.post("/url/to/HereIsSomeJSON", oPostDatas, function(oData, sStatus) {
// Here is the job to be done with the fetched JSON
}, "json");
}
Everything works just fine thanks to the request.method verification I do in the view. The user isn't able to manually (by entering my AJAX url in his browser) access to my view.
However, as I will need more AJAX views I was wondering if I was doing the right thing. So I thought of creating a custom Django decorator which I could use above every one of my AJAX views.
Is is the good way of protecting my private views ? And if so, how do I do it ?
Thanks,
Edit
Apparently, this was not clear enough. I am using a Django view to do an AJAX request. But I don't want the user to be able to type in the URL to read database contents. I know one could always use curl or something similar to send POST datas and thus bypassing my thing, even though he would have to send the right {% csrf_token %}.
Plus, in a near future the login feature will be implemented and I will add the @login_required decorator.
Thanks,