Client-side django template with jQuery
with jQuery and [jQuery templates](http://plugins.jquery.com/project/jquerytemplate) you can use the django template language on the client-side with javascript.
- template
- jquery
with jQuery and [jQuery templates](http://plugins.jquery.com/project/jquerytemplate) you can use the django template language on the client-side with javascript.
Parse a string for [BBCode](http://en.wikipedia.org/wiki/Bbcode) and generate it to (X)HTML by using the [postmarkup libary](http://code.google.com/p/postmarkup/). In your template for generating (X)HTML: {% load bbcode %} {{ value|bbcode }} In your template for removing BBCode fragments: {% load bbcode %} {{ value|strip_bbcode }}
RowCacheManager is a model manager that will try to fetch any 'get' (i.e., single-row) requests from the cache. ModelWithCaching is an abstract base model that does some extra work that you'll probably want if you're using the RowCacheManager. So to use this code, you just need to do two things: First, set objects=RowCacheManager() in your model definition, then inherit from ModelWithCaching if you want the invalidation for free. If you are unusually brave, use the metaclass for ModelWithCaching and you won't even need the "objects=RowCacheManager()" line.
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.)
Adds an 'X-Django-Request-Time' HTTP response header that times how long django spent processing the request.
This is a subclass of Django's built-in JSONEncoder that adds the ability to output form and field objects as ExtJS-compatible config objects. Simple example: from django.utils import simplejson json = { 'data': [], 'success': True, 'metaData': { 'fields': SFY09RDOForm(), 'root': 'data', 'successProperty': 'success' }, } return HttpResponse(simplejson.dumps(json, cls=ExtJSONEncoder)) Where SFY09RDOForm is a subclass of django.forms.Form. 6/20/2008: Updated to pass on the help_text parameter (useful in combination with this override in ext: http://extjs.com/forum/showthread.php?t=36642)
A clean_<fieldname>() method in a form subclass as described [here](http://www.djangoproject.com/documentation/newforms/#custom-form-and-field-validation). Scans the field named *file* for viruses. My version of python-clamav does not support scanning of buffers. That is why I go through the hassle of saving the file to a temporary one.
Some functions and newforms fields for validating credit card numbers, and their expiry dates. In my project, I have all of the credit card functions in a file called creditcards.py Just as an overview: To validate a credit card number there are a few steps: 1. Make sure the number only contains digits and spaces. `ValidateCharacters()` 2. Remove spaces so that only numbers are left. `StripToNumbers()` 3. Check that the number validates using the Luhn Checksum `ValidateLuhnChecksum()` 4. Check to see whether the number is valid for the type of card that is selected. This is annoying because you will need to look at another cleaned field before you can check this.
**Attention: this snippet depends on jQuery library to works** The Admin templates hierarchy does not allow you change the submit line (that buttons bar in the footer of the change view of a model class). This code shows how to resolve this, using a simple javascript trick. You can read the code and implement using your favorite javascript library (instead of jQuery) or pure JavaScript. This example regards to User Profile, a common used model class that adds custom fields to a user in the authentication system. To use this, you must put this template code in a file with the following name: templates/admin/auth/user/change_form.html
Banning middleware with allow,deny functionality. Can select by User id/username and IP addresses. Returns a HttpResponseForbidden when banning requests. Banning by users is real nice because no matter which IP a pest comes from, they can never retrieve anything that they log into. Very handy for keeping out those unwanted pests! I personally developed this further to use a Ban model to keep track of different bans on different sites. Maybe ill post that eventually, but this runs as is with static vars. Implementation from [HvZ Source](http://www.hvzsource.com)
Serving KML from your Django webapp to feed Google-earth isn't that hard, it's just some fun with templates, plus some headers. But serving a compressed version of your KML needs a trick. KMZ isn't just zipped KML. A good KMZ file is a zipped file that decompress to a file called 'doc.kml', which is a KML file. So, I suppose 'http://yourdomain.com/kml/' points to a view generating a well-formed KML. I even suppose that 'http://yourdomain.com/kmz/' points to the same view, but it will serve KMZ instead that KML: no change needed in your code! If your webapps serves more than one KML file you just need to append the new KMZ urls to your urls.py, pointing to the very same view serving the KML version. Then add that urls to the list in this middleware. As an example I included a 'http://yourdomain.com/kml/restricted/' to 'http://yourdomain.com/kmz/restricted/' conversion.
Creates a template tag called "split_list" which can split a list into chunks of a given size. For instance, if you have a list 'some_data', and you want to put it into a table with three items per row, you could use this tag: {% split_list some_data as chunked_data 3 %} Given a some_data of [1,2,3,4,5,6], the context variable 'chunked_data' becomes [[1,2,3],[4,5,6]] This is useful for creating rows of equal numbers of items. Thanks to the users of #django (pauladamsmith, Adam_G, and ubernostrum) for advice and pointers, thanks to Guyon Morée for writing the chunking recipe that this tag is based on.
Sometimes i like to try things out in a blank django project, so i created a python script which creates an out of the box working project skeleton for me: $ djangoskel.py project_name
I love newforms. But sometimes using ``{{ form }}`` within a template doesn't give you enough flexibility. The other option, manually defining the markup for each field, is tedious, boring and error-prone. This is an example of how you can use a template filter to get the best of both worlds. Use it like this to render an entire form: ``{% for field in form %}`` {{ field|form_row }} ``{% endfor %}`` Or use it on a per-field basis: ``<fieldset>`` {{ form.first_name|form_row }} {{ form.last_name|form_row }} ``</fieldset>``
The default 500 handler does not take into consideration if the HTTP request made is an XMLHttpRequest. If it's an XHR, then it may not be a good idea to send back your default 500 HTML page. To use this custom 500 handler, just add the following to your urls.py: handler500 = 'my_project.my_app.views.my_500'
3110 snippets posted so far.