Based on Snippet [766](http://www.djangosnippets.org/snippets/766/) but added syntax highlighting of the sql output via [pygments](http://pygments.org/). The sql output will also be wrapped at 120 characters by default (can be configured by changing WRAP). It degrades nicely if pygments is not installed. This will add quite some cpu-cycles just for printing debug messages so use with care.
Following is the rest of the original description by [simon](http://www.djangosnippets.org/users/simon/) (shamelessly copied):
Adds a hidden footer to the bottom of every text/html page containing a list of SQL queries executed and templates that were loaded (including their full filesystem path to help debug complex template loading scenarios).
To use, drop into a file called 'debug_middleware.py' on your Python path and add 'debug_middleware.DebugFooter' to your MIDDLEWARE_CLASSES setting.
Edit: Added the ability to set the height of the debug-box
This is intended as an alternative to http://www.djangosnippets.org/snippets/155/
Put this in your own cache.py and import it instead of django.core.cache and use it the same way. We left out the "add" function but it shouldn't be too hard to make if you want it.
From the above post: "The purpose of this caching scheme is to avoid the dog-pile effect. Dog-piling is what normally happens when your data for the cache takes more time to generate than your server is answering requests per second. In other words if your data takes 5 seconds to generate and you are serving 10 requests per second, then when the data expires the normal cache schemes will spawn 50 attempts a regenerating the data before the first request completes. The increased load from the 49 redundant processes may further increase the time it takes to generate the data. If this happens then you are well on your way into a death spiral
MintCache works to prevent this scenario by using memcached to to keep track of not just an expiration date, but also a stale date The first client to request data past the stale date is asked to refresh the data, while subsequent requests are given the stale but not-yet-expired data as if it were fresh, with the undertanding that it will get refreshed in a 'reasonable' amount of time by that initial request."
Checks if the request is an AJAX request, if not it returns an HttpResponseNotFound. It looks for the XMLHttpRequest value in the HTTP_X_REQUESTED_WITH header. Major javascript frameworks (jQuery, etc.) send this header in every AJAX request.
Observation: depends on jQuery to works!
This widget works like other multiple select widgets, but it shows a drop down field for each choice user does, and aways let a blank choice at the end where the user can choose a new, etc.
Example using it:
class MyForm(forms.ModelForm):
categories = forms.Field(widget=DropDownMultiple)
def __init__(self, *args, **kwargs):
self.base_fields['categories'].widget.choices = Category.objects.values_list('id', 'name')
super(MyForm, self).__init__(*args, **kwargs)
Example usage of the GChartWrapper.charts module for creating dynamic charts with templatetags. It is an easy method of creating dynamic GoogleCharts from the [GoogleChartAPI](http://code.google.com/apis/chart/). The project is located at [google-chartwrapper](http://code.google.com/p/google-chartwrapper/). To get the most recent version:
`svn checkout http://google-chartwrapper.googlecode.com/svn/trunk/`
and run `python setup.py` in the downloaded trunk directory. There is an included django project there with the [ChartsExamples](http://code.google.com/p/google-chartwrapper/wiki/ChartExamples) all worked out in django templates
This is a little snippet that you can use to make your Django newforms dynamic at runtime. You can define an arbitrary number of fields of the form without loosing newforms capibilites.
You can render the form dynamically be "misusing" the "help_text" attribute of the form fields (Every form field allows the definition of this attribute). This way you can search for changes in the help_text of every field and render the form accordingly.
The form itself is dynamically defined in the view.
The form state can be saved in a Django Session Variable (specifically for Linux users with a process-based Apache Server), so that you can rebuild and verify a submitted form.
Django's test client is very limited when it comes to testing complex interactions e.g. forms with hidden or persisted values etc. Twill excels in this area, and thankfully it is very easy to integrate it.
* Use `twill_setup` in your `TestCaseSubClass.setUp()` method
* Use `twill_teardown` in `TestCaseSubClass.tearDown()` method
* In a test, use something like `make_twill_url()` to generate URLs that will work for twill.
* Use `twill.commands.go()` etc. to control twill, or use `twill.execute_string()` or `twill.execute_script()`.
* Add `twill.set_output(StringIO())` to suppress twill output
* If you want to write half the test, then use twill interactively to write the rest as a twill script, use the example in `unfinished_test()`
Twill will raise exceptions if commands fail. This means you will get 'E' for error, rather than 'F' for fail in the test output. If necessary, it wouldn't be hard to wrap the twill commands to flag failure with TestCase.assert_
There are, of course, more advanced ways of using these functions (e.g. a mixin that does the setup/teardown for you), but the basic functions needed are here.
See also:
* [Twill](http://twill.idyll.org/)
* [Twill Python API](http://twill.idyll.org/python-api.html)
I like to keep all local settings files in my versioning repository. The way I differentiate between them is by querying the hostname of the local machine. I've got a host_settings folder with local settings files. Notice that the local settings file names go by a convention where '.' is replaced with underscores.
Example: host_settings/local_machine_tld.py
Simply adds an attribute `is_ajax` to a request object, indicating if the request was made via Ajax. Allows you to reuse a lot of POST processing view code to which you'd like to progressively add Ajax:
`if request.is_ajax: return JsonResponse(some_json)`
`else: return render_to_response('some_template.html')`
Sometimes it can be time consuming to go through a bunch of objects in Django's
Admin if you only need to update one field in each. An example of this is an
`order` field that allows you to manually set the order for a queryset.
**This snippet contains examples of how to set up the Admin list_display to
make Ajax calls to a custom view.**
The following code may not be worthy of being a snippet, it's all pretty
straightforward, but here it is for those who just want to copy-and-paste.
Sometimes you want to create a temporal variable to store something or do anything you want with it, problem is that django template system doesn't provide this kind of feature. This template tag is just for that.
Syntax::
{% assign [name] [value] %}
This will create a context variable named [name] with a value of [value]
[name] can be any identifier and [value] can be anything. If [value] is a callable, it will be called first and the returning result will be assigned to [name]. [value] can even be filtered.
Example::
{% assign count 0 %}
{% assign str "an string" %}
{% assign number 10 %}
{% assign list entry.get_related %}
{% assign other_str "another"|capfirst %}
{% ifequal count 0 %}
...
{% endifequal %}
{% ifequal str "an string" %}
...
{% endifequal %}
{% if list %}
{% for item in list %}
...
{% endfor %}
{% endif %}
If you want unique values for a slug field, but don't want to bother the user with error messages, this function can be put into a model's save function to automate unique slugs. It works by appending an integer counter to duplicate slugs.
The item's slug field is first prepopulated by slugify-ing the source field. If that value already exists, a counter is appended to the slug, and the counter incremented upward until the value is unique.
For instance, if you save an object titled Daily Roundup, and the slug daily-roundup is already taken, this function will try daily-roundup-2, daily-roundup-3, daily-roundup-4, etc, until a unique value is found.
Call from within a model's custom save() method like so:
`unique_slug(item, slug_source='field1', slug_field='field2')`
where the value of field slug_source will be used to prepopulate the value of slug_field.
Comments appreciated!
**How to use:**
1. puts this code at the end of the `models.py` file who haves the User Profile class declared;
2. verify if your User Profile class has the name 'UserProfile'. If not, change the code to the right name.
**About:** this snippet makes the ORM create a profile each time an user is created (or updated, if the user profile lost), including 'admin' user.
The script that can be used to profile any Django-powered web-site and find how many SQL-queries are used per page, how heavy html-pages are, etc.
To use the the script it's enough to put django-profile.py somewhere in PYTHONPATH and call it from the directory that holds projects' settings.py.
For more info and examples please see:
[www.mysoftparade.com/blog/django-profile-sql-performance/](http://www.mysoftparade.com/blog/django-profile-sql-performance/)
This Update adds requested support for self referential fields.
This is useful if you need to compute and store potentially hundreds or thousands of objects and relationships quickly. To perform the inserts it will hit the database 1 plus N/100 times per affected table and where N is the number of rows to be inserted. It will use INSERT or LOAD DATA INFILE on MySQL.
Run this on your test database first and make sure all of your field defaults and null values are set appropriately as you could attempt to insert a NULL where it isn't allowed and end up with a partial insert.
This code is reasonably well tested and has been used for database pre-loading and operations on live sites.
My test suite, however, is focused on my own use cases. Any input, i.e. failures, for creating more tests would be appreciated.
Lots of Details in the Doc String.
Currently only MySQL, however there is some crude skeleton code to support other databases.
You're looking at the most-bookmarked snippets on the site; if you'd like to help useful snippets show up here, sign up for an account and you'll get your own bookmarks list.