SWFUpload with Django 1.2 csrf problem - django

I`m trying to upload files to Django with SWFUpload. Found this article Django with SWFUpload. But found one problem. In Django 1.2 a csrf requires a csrf token to be send on every form submit, and it includes files that are send with SWFUpload.So uploading doesnt until i turn off csrf ( globally or for view using #csrf_exempt decorator). Is there a better way to handle this rather than turning off csrf?
I know that i can pass custom data with SWFUpload post_params: {"csrfmiddlewaretoken" : ""},. But i don`t know how to get only value of csrf token in template, not a full input tag.

To retrieve the csrf token itself, you'll need to resort to using some of Django's internals. First off, include this line at the top of your view.
from django.middleware.csrf import get_token
Now, when passing parameters to your template, do something like
def my_view(request):
return render_to_response("index.html", {"csrf_token": get_token(request)})
In your template, just reference the token with {{ csrf_token }}.

Related

Avoid csrf token in django post method

I am making part of the web app where (unlogged users, all visitors) can fill the form and I have to save that data (name, phone number, question) in database..
I am making REST using Django, but for frontend I will use React or Django, and I am making POST method in Django framework that reads JSON data from POST https request, and then I save that data to database.. But I get error CSRF verification failed. Request aborted. because I don not use CSRF token, because it is not required for this (I do not have logged users).
But I do not want to disable CSRF, because for admin page I would use this to authenticate users?
So anyone knows how to avoid using CSRF token for this method? Thanks in advance..
def saveDataToDatabase(request):
if request.method == 'POST':
json_data = json.loads(request.body)
try:
data = json_data['data']
except KeyError:
HttpResponseServerError("Malformed data!")
This is the part of method..
It's possible to disable csrf protection on a view with #csrf_exempt decorator.
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def saveDataToDatabase(request):
# Your code here
More Infos on the Django doc
Have you thought about using Views to handle the requests? You may use these so you don´t have to do the next advice I´m giving you.
If the first advice wasn´t good enough, you may disable the csrf token in the settings file from Django. You need to remove (or comment) the django.middleware.csrf.CsrfViewMiddleware in the available Middleware list.
Any other question just ask. ;)

Django csrf token

views.py
from django.core.context_processors import csrf
context.update(csrf(request))
{'csrf_token': <django.utils.functional.__proxy__ object at 0xae0f4ec>}
I am trying to add csrf token to my forms.i m generating csrf token in the views like above.But csrf_token value gives some proxy object like the one shown above instead of string.I m using django 1.3.Thanks in advance for any sort of help.
The csrf method is lazy, it returns a Promise/Proxy. Once this object is called in the template, the template engine will unicode this object which triggers the real method.
Try this:
print unicode(csrf(request)['csrf_token'])

How to convert a Django HttpResponse to a Django render call

I have the following code
def ajax_login_request(request):
try:
request.POST[u'login']
dictionary = request.POST
except:
dictionary = request.GET
user = authenticate(username = dictionary[u'login'], password = dictionary[u'password'])
if user and user.is_active:
login(request, user)
result = True
else:
result = False
response = HttpResponse(json.dumps(result), mimetype = u'application/json')
return response
which is being called via ajax. I'm a noob and this is from an example in a book. Unfortunately the version of Django I'm using throws a CSRF error on this. I've done the other CSRF bits, but I don't know how to change the HttpResponse bit to a render call. I do not want to use CSRF_exempt, because I have no idea when that is appropriate. Can someone please provide me the equivalent render call for the HttpResponse above.
Thanks
To make your original code work, you need to get a RequestContext object and pass it along with your response, something like this:
from django.http import HttpResponse
from django.template import RequestContext, Template
def ajax_login_request(request):
# ...
# This bit of code adds the CSRF bits to your request.
c = RequestContext(request,{'result':json.dumps(result)})
t = Template("{{result}}") # A dummy template
response = HttpResponse(t.render(c), mimetype = u'application/json')
return response
Do read up on the CSRF documentation as you might run into strange errors if you don't understand all the ways CSRF is "wired" in your app. The page also has a javascript snippet to make sure CSRF cookies are sent with your ajax requests if you are sending them without a form.
You can also use the render_to_response() shortcut, but you would need to have an actual template to load (in your case, you don't need a template, hence the "dummy" template in my example).
Ok, I'm going to re-draft this answer so you understand where I'm coming from. The CSRF middleware works like this:
You make request -------> request hits csrf --(invalid/no token)--> render 403
middleware
|
(valid token)
|
\ /
Call view
|
\ /
middleware sets
csrf cookie
|
\ /
Response appears
In other words, if you are seeing a 403 csrf page, your view was never called. You can confirm this by sticking a spurious print statement in the view and watching the output from runserver when you make your request.
To solve this, you either need to disable csrf (not good) or use one of the ajax methods available to you. If the required token is passed in your view will actually be executed.
The reason your view is not called is to prevent the action from the forged site from actually ever taking place - for example, if you denied the template at response time the user would already be logged in. The same behaviour occurs with the function decorators.
As for the middleware setting the cookie, that does not alter or depend on the render function at all - this sets the HTTP header Cookie: ... in the response. All responses in Django are HttpResponse objects until it finally converts them to output; render functions are helpers, but that's not what's causing your problem here.
Edit I'll convert what you've got to a render call. You could do this:
return render_to_response(`ajax_templates/login_response.html`,
{'loginresponse': json.dumps(result)})
Where ajax_templates/login_response.html is just:
{% loginresponse %}
That's it. HttpResponse has a main default argument which is the string to return (literally, the html of the web page); that's what you're doing initially. render_to_response and render are shortcuts to this which do this:
render_to_response called ----> open template asked for --> substitute arguments
|
\ /
django instructs web server <--- return this from view <-- create HttpResponse
to send to client object

Using flatpages to create a simple facebook app, but CSRF problem caused by signed_request

I am trying to create a simple, html-only facebook app for a client's fb page. I would like to use django's flatpages so that the client and his staff can change the content of the app through the django admin of their site. The problem is that Django returns a 403 "CSRF verification failed. Request aborted." error when facebook attempts to send its own POST info and access the url of the app.
I already know about the #csrf_exempt decorator, but I am not sure how I would apply it to the flatpage view, as it is within the django.contrib code. Furthermore I would only want to disable csrf protection when the view is asked to call a specific facebook.html template (not not the default.html template). If there happened to be a {% crsf_exempt %} template tag for example, that would be perfect.
Can anyone think of a way to resolve this problem? Or maybe I should give up on the idea of using the django-flatpages to serve the facebook app?
Try using this decorator on your views that are called facebook:
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
this will disable csrf protection on that view.
Does this help?
I ran into the exact same problem as you. I wanted to diable csrf for flatpages (but not for the rest of the site) and ended up with the following middleware:
class DisableCSRFOnFlatPages(object):
def process_request(self, request):
try:
FlatPage.objects.get(url=request.META.get('PATH_INFO'))
setattr(request, '_dont_enforce_csrf_checks', True)
except FlatPage.DoesNotExist:
return
Add it to your settings and it should disable the csrf check whenever there's a flatpage.

Django CSRF problems with cookies disabled

While testing an application I've written in Django, I've found that I'm be thrown a HTTP 403 Forbidden error every time I submit a form. I am aware that the CSRF middleware checks for a cookie with the CSRF token - but what should my approach be given a user that has cookies disabled?
Do I need to be checking whether the user has cookies enabled in each of my views or is there a more efficient approach?
Thanks in advance.
This question dealt with Django pre-1.2 -- the solution is different if you have an older version.
Starting in Django 1.2 you can override the 403 response using CSRF_FAILURE_VIEW.
Just for anyone who has the same problem: I found that the best suited solution for me was writing some middleware that displays a generic 403 error page:
from django.http import HttpResponseForbidden
from django.conf import settings
from django.template import RequestContext
from django.shortcuts import render_to_response
class PermissionErrorMiddleware(object):
def process_response(self, request, response):
if isinstance(response, HttpResponseForbidden):
return render_to_response('403.html', context_instance=RequestContext(request))
return response
It instructs the user that the most likely cause for the error page is that cookies are disabled (among other things), because my application doesn't really throw 403 errors otherwise. I have always preferred the "security through obscurity" approach, and throw 404 errors when a user shouldn't be accessing a particular page.
If the form really must work without cookies, I think you just have to disable the CSRF middleware. You might be able to implement something similar using two form inputs where the value of one is random, and the other is a hash of the fist one and a secret.
Did you try to pass csrf information as a hidden POST variable? In projects that I have been involved in it is usually done with a hidden input:
<input type="hidden" name="csrf" value="<?=$person->csrf?>" />
Sorry for PHP code, I don't remember how to do it in Django Templates.