Get boolean value from request send by Ajax
gets the value from request and returns it's boolean state
- ajax
- django
- request
- post
gets the value from request and returns it's boolean state
This is based on the Admin app functionality for dispatching calls. Once you put these two files in place then add the following to urls.py: from myProject import ajax urlpatterns = patterns('', ... # Add this to the urlpatterns list (r'^ajax/(.*)', ajax.dispatcher.urls), ...) you register a function or method with a name like so: from django.contrib import ajax def myAutoCompleteCall(request): ... ajax.dispatcher.register('myAutoComplete', myAutoCompleteCall) Then you can use the url: `http://www.mysite.com/ajax/myAutoComplete` Previously I had placed this app in the django\\contrib directory because I wanted to use it in an Admin app mod. Since the release of 1.1 I was able to move it out into a standard app because of the new `formfield_overrides` property of the `ModelAdmin` class.
Inserts the output of a view, using fully qualified view name (and then some args), a or local Django URL. {% view view_or_url arg[ arg2] k=v [k2=v2...] %} This might be helpful if you are trying to do 'on-server' AJAX of page panels. Most browsers can call back to the server to get panels of content asynchonously, whilst others (such as mobiles that don't support AJAX very well) can have a template that embeds the output of the URL synchronously into the main page. Yay! Go the mobile web! Follow standard templatetag instructions for installing. **IMPORTANT**: the calling template must receive a context variable called 'request' containing the original HttpRequest. This means you should be OK with permissions and other session state. **ALSO NOTE**: that middleware is not invoked on this 'inner' view. Example usage... Using a view name (or something that evaluates to a view name): {% view "mymodule.views.inner" "value" %} {% view "mymodule.views.inner" keyword="value" %} {% view "mymodule.views.inner" arg_expr %} {% view "mymodule.views.inner" keyword=arg_expr %} {% view view_expr "value" %} {% view view_expr keyword="value" %} {% view view_expr arg_expr %} {% view view_expr keyword=arg_expr %} Using a URL (or something that evaluates to a URL): {% view "/inner" %} {% view url_expr %} (Note that every argument will be evaluated against context except for the names of any keyword arguments. If you're warped enough to need evaluated keyword names, then you're probably smart enough to add this yourself!)
For most applications, simplejson.dumps() is enough. But I’m especially fond of iterators, generators, functors (objects with a `__call__()` method) and closures, dense components that express one thought well: the structure of a tree, or the rows of a database, to be sent to the browser. The routine dumps() doesn’t understand any of those things, but with a simple addition, you can plug them into your code and be on your way without headache. Dumps() just calls JSONEncoder(), and JSONEncoder has a routine for extending its functionality. The routine is to override a method named default() (why “default?” I have no idea) and add the object types and signatures you want to send to the browser. Normally, this exists for you to provide custom “object to JSON” handlers for your objects, but there’s nothing custom about iterators, generators, functors and closures. They are native Python objects. This snippet provides the functionality needed by JSONEncoder to correctly dereference these useful Python objects and render their contents. (Originally posted [here](http://www.elfsternberg.com/2009/05/20/fixing-an-omission-from-djangos-simplejson-iterators-generators-functors-and-closures/) )
A helper.
Some ajax heavy apps require a lot of views that are merely a wrapper around the form. This generic view can be used for them.
Often its useful to get error information for ajax/javascript errors happening on various clients. This can go to something like this: # error_sink def error_sink(request): # post request, with event name in "event", and event data in "data" context = request.REQUEST.get("context", "") context = cgi.parse_qs(context) context["data"] = cgi.parse_qs(context.get("data", [""])[0]) context["user"] = request.vuser context["referrer"] = request.META.get('HTTP_REFERER', "referrer not set") context = pformat(context) send_mail( "ajax error", context, "[email protected]", ["[email protected]",], fail_silently=True ) return JSONResponse({"status": "ok" }) # }}}
Sample jQuery javascript to use this view: $(function(){ $("#id_username, #id_password, #id_password2, #id_email").blur(function(){ var url = "/ajax/validate-registration-form/?field=" + this.name; var field = this.name; $.ajax({ url: url, data: $("#registration_form").serialize(), type: "post", dataType: "json", success: function (response){ if(response.valid) { $("#"+field+"_errors").html("Sounds good"); } else { $("#"+field+"_errors").html(response.errors); } } }); }); }); For each field you will have to put a div/span with id like fieldname_errors where the error message will be shown.
This code will allow you to use chained select boxes in the django automatic admin area. For example, you may have a product, then a category and subcategory. You'd like to create a product, and then choose a category, and then have a chained select box be filled with the appropriate subcategories.
This snippets is a simple contact form for use meteora widgets with django For download the meteora.js and all tools http://meteora.astrata.com.mx
Another sample of how to integrate Django and jQuery. === This starts a function in views.py that takes a long time to finish. It sets a session variable so that another function can report on the situation. We use jquery and ajax to 'pull' that data from Django so as to provide a progress report. I don't yet know how to background a long-running process, but this is an okay stop-gap method to use. I hope. \d
I recently got a form working via jQuery and Django. This was not easy for me to do and I thought I'd record my finding here. The form submits via jQuery and the "form" plugin. Please visit jQuery's home page to find all those links. This code handles: * urls.py -- passing both normal and 'Ajax' urls to a view. * views.py -- Handling both kinds of requests so that both normal and ajax submits will work. * The HTML template with the script for submitting and some bling. Error handling === I like to stay DRY so the idea of checking the form for errors in javascript *and* checking it in Django irks me. I decided to leave that up to Django, so the form submits and gets validated on the server. The error messages are sent back to the browser and then displayed.
More: http://gist.github.com/3247
Whip up an AJAX API for your site in a jiffy: class MySite(AJAXApi): @AJAXApi.export def hello(request): return {'content': self.get_content()} def get_content(self): return 'Hello, world!' urlpatterns += MySite().url_patterns() (the example needs the JSON encoding middleware of [snippet 803](http://www.djangosnippets.org/snippets/803/) to work.) The secret is that bound instance methods are callable too, so work as views. (Most Django people only use functions, or sometimes classes with `__call__`, as view functions.) You get implicit type dispatch off that `self` object. So you could subclass `MySite`, change `get_content`, and still use the same `hello` method. See (django-webapp)[http://code.google.com/p/django-webapp/] for a REST-ish Resource class using this same idea. You can clearly do better than my `func_to_view`, and also make a better decorator than `exported` (so you can actually say `@exported('name') def function()` etc.). This is more of a proof of concept that should work for most people. Caveat: I've changed a few things since I last really tested this. (psst, this also works for non-AJAX views too.)
Handles exceptions from AJAX code, giving more useful errors and tracebacks. (By the way, all these new snippets are extracts from [django-webapp](http://code.google.com/p/django-webapp/).) This exact code is not well tested, but it's refactored from some code we use in production.
51 snippets posted so far.