In test code, it is sometimes useful to monkeypatch a Django method to have stubbed out behavior, so that you can simplify data setup. Even with decent data setup you might want to avoid execution of Django code that is not the target of your test.
The code snippet shown here illustrates a technique to limit the scope of your monkeypatches. It uses the Python "with" statement, which was introduced in 2.5.
[with statement](http://effbot.org/zone/python-with-statement.htm)
The key aspect of the "with" machinery is that you can set up an __exit__ method that gets called even if the code inside the "with" raises an exception. This guarantees that your monkeypatch gets un-monkeyed before any other code gets called.
I don't recommend monkeypatches in production, but if you HAVE to resort to a monkeypatch, I definitely advise using "with" to limit their scope.
The examples on the left illustrate how to suppress versions of reverse() and timesince()--look at the import statements to see which ones I am talking about. Obviously, monkeypatching is not for the faint of the heart, as you need to be able to find the code to monkeypatch in Django source, and you need to be sure there aren't decorators at play.
Save this shell script to the root of your Django project as "tags.sh", make it executable with "chmod +x tags.sh", and run it from the project root with "./tags.sh", and you will have a "tags" file for vim and a "TAGS" file for emacs.
Tags will be created for Python, JavaScript, and block names found in HTML templates. You may need to change "/usr/share/pyshared/django" to the location of your Django installation.
Documentation on [Tags in emacs](http://www.gnu.org/software/emacs/manual/html_node/emacs/Tags.html) | [Tags in vim](http://vimdoc.sourceforge.net/htmldoc/tagsrch.html)
By default, a "Show all" link will appear in the changelist pager only if fewer than 200 records are in the result. Since it is rare that there will be more than one page of records yet fewer than 200, the "Show all" link almost never shows up. Pasting this code somewhere in your app will allow you to increase the 200-record maximum.
"Show all" is very handy when used in combination with batch actions and filters, and this change will enable it for most situations. Note that this allows a changelist with up to 10,000 results, which results in a lot of HTML that can tax slower browsers and older machines. For me, it has been worth the tradeoff, since my users have fast enough computers and need to be able to make batch changes efficiently.
Returns a list of date objects for a given number of past days, including today. Useful for summaries of recent history.
Inspired by [Template range filter](http://www.djangosnippets.org/snippets/1357/)
This snipped removes a specific fields from the fieldsets. This is very useful to leave a field 'out' in the admin, likewise:
def get_fieldsets(self, request, obj=None):
fieldsets = super(BlaModelAdmin, self).get_fieldsets(request, obj)
if not request.user.has_perm('change_blah'):
remove_from_fieldsets(fieldsets, ('blah',))
This is a custom template tag that clears the cache that was created with the **cache** tag.
{% load clearcache %}
{% clearcache [fragment_name] [var1] [var2] .. %}
Create **app/templatetags** folder with **__init__.py** and copy code into **clearcache.py** file.
polls/
templatetags/
__init__.py
clearcache.py
Based on django.templatetags.cache. See Django docs on [custom template tags](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/)
There are times when you want to hook into the Variable class of django.template to get extra debugging, or even to change its behavior. The code shown is working code that does just that. You can monkeypatch template variable resolution by calling patch_resolver(). I recommend using it for automated tests at first.
My particular version of _resolve_lookup does two things--it provides some simple tracing, and it also simplifies variable resolution. In particular, I do not allow index lookups on lists, since we never use that feature in our codebase, and I do not silently catch so many exceptions as the original version, since we want to err on the side of failure for tests. (If you want to do monkeypatching in production, you obviously want to be confident in your tests and have good error catching.)
As far as tracing is concerned, right now I am doing very basic "print" statements, but once you have these hooks in place, you can do more exotic things like warn when the same object is being dereferenced too many times, or even build up a graph of object interrelationships. (I leave that as an exercise to the reader.)
If you want to see what the core _resolve_lookup method looks like, you can find it in django/templates/__init__.py in your installation, or also here (scroll down to line 701 or so):
[source](http://code.djangoproject.com/browser/django/trunk/django/template/__init__.py)
We often need to use a Profile form and we want to be able to modify the first_name, last_name and sometimes the email address.
Here is how I do it.
In this case I want to check the email so I did a specific form for it. But it is quite easy to add it.
This is a basic model view for exporting data from models. It is designed so that you can provide the GET variables used for searching/filtering within listdisplay pages in the admin, and the code will filter the same way.
It allows the output of model data in various formats using serializers or templates.
This is a really simple snippet , but is not documented well ...
Whit this , you can limit the output of one field in 25 characters before you test that is equal or over 30 characters!
Note that the snippet cut the text and add three points at the end (...)
Enjoy!
A bit cleaner syntax for method attribute assignment; used in models for 'short_description'.
>from mysite.polls.models import Poll
>poll = Poll.objects.get(pk=1)
>poll.was_published_today.short_description
>>>'Published today?'
A simple replacement for Django's default GZipMiddleware which breaks when trying to serve files or pass any kind of iterators to the HttpResponse object.
Simply replace GZipMiddleware with the provided middleware and set response.dontgzip = True when returning the response, and it will then be ignored by the middleware.
This snippet is used in conjunction with the code in [#1779](http://www.djangosnippets.org/snippets/1779/) to make an mptt-enabled version of the FilteredSelectMultiple widget.
See my blog for full details:
[http://anentropic.wordpress.com](http://anentropic.wordpress.com/2009/11/05/more-django-mptt-goodness-filteredselectmultiple-m2m-widget/)
You're looking at the top-rated snippets currently on the site; if you'd like to contribute, sign up for an account and you'll be able to rate any snippet you see.