I have a React SPA with a Django backend. Like most SPAs, there is an index.html file that needs to be served. But the problem is that this file is served with nginx, so user does not obtain csrf token required to make api calls. I don't really want to serve index.html, as it would require separating the file from the rest of npm run build output and break the "just put it in /static/ directory" workflow, and also for caching reasons. Is there any other workaround?
CSRF token is always updated with each page load. It has to be served by django since django is the application that provides and validates it. Place the index.html file in your django templates folder, serve it with your index view, translate CSRF token to javascript code and use it in your ReactJS code
index.html
...
<body>
<script>
var csrftoken = '{{ csrf_token }}';
</script>
...
</body>
...
Related
I have an SPA with Django on backend. I try to make it a progressive web app. I made a manifest.json and linked it in my index.html:
<link rel="manifest" href="/static/manifest.json">
Chrome can't detect it. My index.html is a Django template and is stored in templates directory and can't be accessed but by Django route /. Manifest.json is in static directory and served to front-end as a regular static file. I think this is the reason manifest can't be detected - index.html not being accessible. Am I right? If so, could you give me an advice as to how to make it work please?
Try
load static
{% static "manifest.json" %}
The syntax here is {% static "path/relative/to/static/folder" %}
My django(2.1) app needs to be able to be embedded in an iframe in a partner's website. I'm currently running it on google app engine where I have the following app.yaml settings:
handlers:
- url: /.*
static_dir: static/
secure: always
http_headers:
Content-Security-Policy: "frame-ancestors 'self' partnersite .com *.partnersite.com www.partnersite.com;"
I can now access the login page through the partner site but when I try to log in I get the following error:
CSRF verification failed. Request aborted.
Reason given for failure:
CSRF cookie not set.
The templates have {% csrf_token %} tags. I'm stumped, if anyone has any help or feedback please let me know.
I have a Django app with about a dozen views that I am currently hosting on Heroku. I can do POST requests just fine to the app when directly going to the app url, and I have the 'django.middleware.csrf.CsrfViewMiddleware' enabled. I am running Django 2.1
I am currently having an issue where I am trying to embed this Django app within an iframe, on another site that I host on Weebly. I always get a 403 error when trying to do a post on any of the Django forms. The reason is "CSRF cookie not set."
I am doing this through Chrome on Ubuntu. I checked the Applications tab in the Developer console, and do see the csrftoken key-value pair set in the cookie for the Heroku domain. The Weebly domain does not contain the csrftoken key-value pair. I figured it would just use the cookie from the Heroku app domain and use the csrftoken, but that doesn't appear to be the case.
In Django, here are my settings regarding CSRF:
CSRF_COOKIE_SECURE = False
CSRF_TRUSTED_ORIGINS = ['example123.herokuapp.com',
'app123.weebly.com']
I REALLY don't want to disable security or use the csrf_exempt decorator, as that feels like a hack. I am pulling my hair out on this one!
EDIT:
{% csrf_token %} is in the form, and I can see the hidden field "csrfmiddlewaretoken":
<input type="hidden" name="csrfmiddlewaretoken" value="XXXXXXXXXXXXXXXXXXXXXXywkFTfTC9ttYiOTD0O8uF49SvRjaUWgWeLU0h2PjP2">
There are two different things with csrf in django
1. Csrfmiddlewaretoken : {% csrf_token %}
example of set-token header
2. CSRFcookie : I don't think that you did this one.
example of same request giving different csrf-token
here the images shown are both the examples of one of my app for a specific request
We do often confuse second with the first one. In the second case, the server sets a cookie in the first get request with a csrf token (this is a cookie and not the csrfmiddlewaretoken ), it needs to be sent every-time for csrf cookie verification. This is done by the browser itself and we mostly don't notice it. However the problem arises with using CORS (different origins of request like android/angular app etc).
I am working on a django project that relies on angularjs and having trouble implementing angular-ui-router framework.
As mentioned in documentation I have included ui.router as a dependency,
app = angular.module('myApp',['restangular','ui.router',])
configured the states as follows,
app.config(['$stateProvider',function($stateProvider){
$stateProvider.state('landing',{
url: '/',
template:"<p> somethings here.</p>"
})
}]);
in base.html file i bootstrap the django project with angularjs as required
ng-app=myApp.
and in index.html which inherits base.html
<div ui-view>
<i>nothing here but this text</i>
</div>
my urls.py,
url(r'^$',home,name="homepage")
This does not work, ui-router never includes the inline template in index.html. index.html always loads nothing here but this text. I have looked at as much questions asked here but are not helping. What am I missing, is this specific to django?
I would say that these lines should make it:
app.config(['$urlRouterProvider',function($urlRouterProvider){
$urlRouterProvider.otherwise('/');
}]);
Check the working plunker here
Also check:
otherwise() for invalid routes
Before posting this i've tried every solution method posted online, including solutions on Stackoverflow and Django. (I think the reason for error perhaps is due to the fact that i'm on a newer verison of jQuery and django and most solutions are dated, using jQuery 1.9 and django 1.5.1)
Here are some URL's to solutions that don't work:
Django CSRF check failing with an Ajax POST request
How to use $.post with django?
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
Any help would be appreciated. Another possibility for error is the fact that i'm not actually sure where to place these snippets exactly. So far i've pasted everything inside the jquery on document load, i've also tried pasting the code in the very start of the .js file. (My javascript code is fragmented in chunks, some are seperate .js files and some are inline with the html being rendered with django context, so any solutions with "{{ csrftoken }}" are bad.
Thanks!!
The CSRF token only gets set if it's present in the template or if the view is decorated with ensure_csrf_cookie(). Putting {% csrf_token %} in index.html will make it apply for all your pages.
From the docs:
The CSRF token is also present in the DOM, but only if explicitly included using csrf_token in a template.
...
If your view is not rendering a template containing the csrf_token template tag, Django might not set the CSRF token cookie. This is common in cases where forms are dynamically added to the page. To address this case, Django provides a view decorator which forces setting of the cookie: ensure_csrf_cookie().
Can you try this:
$.ajax({
type: "POST",
url: '{% url "some_url_which_accepts_post" %}',
data: {'csrfmiddlewaretoken': '{{csrf_token}}', 'comment_id':1},
success: function(data, textStatus){
//something
},
});