Getting 403 error on url while sending POST - python

I am getting started with a django based simple ajax enabled web app.
I am able to launch the hompage. From homepage when i try to hit another url I am getting 403 error
My index page is http://mydomain.com/SampleApp - This works fine
My Ajax url is http://mydomain.com/SampleApp/ajax - This gives 403 error
Please replace 'mydomain.com' in above urls with proper localhost:8000 as it is restricted.
The error shown is
CSRF verification failed. Request aborted.
Reason given for failure:
CSRF cookie not set.
I think I am missing some important setting in settings.py
Adding the source code
URL Conf
url(r'^SampleApp/', include('views.urls'))
views.url.py
urlpatterns = patterns('',
url(r'^ajax/$', views.ajax),
url(r'^$', views.index)
)
views.views.py
def index(request):
print('Rendering Index')
return render(request, 'index.html')
def ajax(request):
print('rendering ajax')
return render(request, 'ajax.html');
For the sake of brevity, I have excluded the imports

It's look like you did not put csrfmiddlewaretoken in your ajax request.
The easiest way to include it is:
var data = {
'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(),
// any other data
},
url = '/api/create/';
$.ajax({
type: 'POST',
url: url,
data: data,
...
And don't forget to include {% csrf_token %} in your template of page from which the ajax request is sent (like index.html)
Or you can decorate your view by #csrf_exempt decorator:
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def ajax(request):
print('rendering ajax')
return render(request, 'ajax.html');
This allows you to exclude csrfmiddlewaretoken from ajax request
Hope that'll help you.

Related

Django request in html

I have set up django to work in my local environment. I have a python function which takes two parameters and returns data in JSON format. This is set up in my views.py and urls.py as follows:
views.py :
from django.http import Http404, HttpResponse
from X import calculate
def calculate_X(request, para1, text):
#para1 is ignored on purpose
return HttpResponse(calculate(text))
urls.py :
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^calculate-X/(\d+)/([a-zA-Z0-9_ ]*$)',calculate_X),
url(r'^$', TemplateView.as_view(template_name='base.html')),
]
urlpatterns += staticfiles_urlpatterns()
In the base.html file I have a single button which should make the request to the calculate-x url as follows /calculate-X/1/stringdataexample
which would then create an alert() with the contents of the httpresponse ( JSON )
How can I make this request?
(There is another question asked here on SO however it uses request processors which do not relate to my question)
one way could be to trigger an ajax call when you click that button, and then process the response as you wish.
The button's html could be something like this:
<button onclick="processCalculation()">Calculate!</button>
Something like this function:
function processCalculation(){
var para1 = $("#params-container").val();
var text = $("#text-container").val();
$.ajax({
url: "/calculate-X/" + para1 + "/" + text,
data: {}
}).done(function (jsonResponse) {
alert(jsonResponse)
});
}
I hope this points you on the right direction, Best regards!

How can I make authenticated request to django view from external html using ajax

I am using django 1.10, I have following html pages register.html, login.html, home.html
Html pages are deployed on different application server. I am using Custom user model,
I can able to register and store details into database. Also able to authenticate and login into app and get redirected to home page.
Problem :
I have sample view named as, test
#viwes.py
#login_required
def test(request):
l=[]
l.append('x')
l.append('y')
return JsonResponse({"records": l})
so after login, when I directly access url as,
localhost:8000/app/test
then I am able to get data in browser.
But after login, within same session, when I am calling same url from home.html, I am not able to authenticate and receive data.
In browser console it will become as,
http://127.0.0.1:8000/accounts/login/?next=/app/test/
There were some posts which refers solution as #ajax_required, as I am new to django, I didn't find any post in detail. Can anyone please explain or suggest solution with sample example. Thanks in advance.
I have tried with below code and working file
views.py
from django.contrib.auth.decorators import login_required
from django.http.response import JsonResponse
from django.views.generic.base import View
class LoginRequiredMixin(object):
#classmethod
def as_view(cls, **initkwargs):
view = super(LoginRequiredMixin, cls).as_view(**initkwargs)
return login_required(view)
class TestLogin(LoginRequiredMixin, View):
def get(self, request, *args, **kwargs):
l = []
l.append('x')
l.append('y')
return JsonResponse({"records": l})
urls.py
from django.conf.urls import url
from django.contrib import admin
from myapp.views import TestLogin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^test/$', TestLogin.as_view(), name='testview'),
]
Curl
curl -X GET -H "Cookie: csrftoken=t1l5CpH7kL5J48yf0c4C0z9kli3UfI3enCEdT4lH8RGQip1y8f8t1l3ucDWWzRGX,sessionid=99oqphuhy1udboq4pv2icgj408b1lpxi" "http://localhost:8000/test/"

How to set Paypal redirect url in django oscar?

I got error while redirecting to local server through https request... i did't find any redirect paypal url settings to change the redirecting url to use http method .. how can i set paypal redircting url manually ?
a terminal error like this
"You're accessing the development server over HTTPS, but it only supports HTTP."
This can be done by subclassing the original express RedirectView class and adding in your custom logic:
views.py
from paypal.express.views import RedirectView as OscarPaypalRedirectView
class RedirectView(OscarPaypalRedirectView):
def _get_redirect_url(self, basket, **kwargs):
return my_url
def _get_paypal_params(self):
""" Send extra paypal params """
return {
'SOLUTIONTYPE': 'Mark',
'LANDINGPAGE': 'Login',
'BRANDNAME': 'My Store',
}
And then you can call this class in in your urls:
from .views import RedirectView,
urls = [
....
....
url(r'paypal/redirect/', RedirectView.as_view(), name='paypal-redirect')
]

Django API Post method returns 403 error

I am trying to setup the Django API (a POST API endpoint). I want to have the same URL path pointing to the same function that handle differently due to if it is POST or GET. Thus, I used the method like this
def handle_post(request):
dict = {}
dict['email'] = "test"
if request.method == "POST":
return HttpResponse(json.dumps(dict), content_type="application/json")
In the url.py, I have the following code
router = routers.DefaultRouter()
router.register(r'notes', UsernotesViewSet)
urlpatterns = patterns('',
url(r'^', include(router.urls)),
url(r'^admin/', include(admin_site.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^docs/', include('rest_framework_swagger.urls')),
url(r'^example/postrequest', handle_post),
)
But I can not get this work when I perform POST onto the URL http://127.0.0.1:8000/example/postrequest?requestid=abc&starthour=10. I did not post anything, but just change the method to POST from GET on httpclient to try this API. Is it ok if I did not post any content to URL ?
I am getting the 403 error, as below :
Forbidden (403)
CSRF verification failed. Request aborted.
You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.
If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests.
Appreciated any help.
I could not understand your question correctly, but CSRF verification failure is caused when "requests via ‘unsafe’ methods, such as POST, PUT and DELETE" are performed without using recommended defense settings against CSRF (Cross Site Request Forgeries).
You can read more on this link.
There is a quick work-around to problem. You can use csrf_exempt decorator to mark a view as being exempt from the protection ensured by the CSRF View Middleware (django.middleware.csrf.CsrfViewMiddleware). Example:
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
#csrf_exempt
def my_view(request):
return HttpResponse('Hello world')
You can read more about is here.
Have a read of the Django docs on CSRF protection. If your api is going to be accessed by javascript in the browser, then there are instructions for how to include the token in an ajax request.
If the API is accessed in a different way e.g. from a mobile client that doesn't use cookies, then it might be appropriate to turn off the CSRF protection for that view, using the csrf_exempt decorator.
Forbidden (403)
CSRF verification failed. Request aborted.
You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.
If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests.
More information is available with DEBUG=True.

CSRF token passing breaks my django view

When passing the X-CSRFToken header or sending csrfmiddlewaretoken in the POST data to my view, it completely skips the ajax handler and goes directly to the index/base view.
Javascript:
$.post("/action/register", {
name: $('#input_name').val(),
email: $('#input_email').val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
}, function(data) {
var response;
try {
response = JSON.parse(data.toString());
} catch(e) {
response = {"status":"error", "message":"Please try again later, we're having some tech issues!"};
}
// ... process some stuff, the callback works which is good
View:
def handle_register(req):
''' Request handler pyfor registration, should return JSON for the AJAX request. '''
if req.is_ajax():
return validate_and_register(req)
else:
return HttpResponse('{"status":"error","message":"Invalid request."}')
urls.py:
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^action/register$', 'views.handle_register', name='handle_register'),
url(r'^admin/', include(admin.site.urls)),
url(r'^.*$', 'views.handle_home', name='handle_home'),
)
When I don't pass the header, i get a 403 (CSRF_VERIFICATION_FAILED). When I pass the appropriate header (confirmed in multiple browsers) it skips the /action/register handler and goes directly to the "handle_home" view.
I'm stuck!
This could possible be due to a missing slash on your url
/action/register
Try adding a slash in url and in your javascript.
Another guess would be:
'views.handle_register'
is missing an app name?
A more safe was as well would be to use reverse urls:
from django.core.urlresolvers import reverse
url = reverse('appname.views.handle_register')
$.post(url, {}, func...
This was an issue with nginx. Per the django/nginx setup docs I found I was missing this in my nginx config:
fastcgi_split_path_info ^()(.*)$;

Categories

Resources