A TimeField that lets you parse a wide variety of freeform-text time descriptions. This doesn't inherit from TimeField because it doesn't use any of its functionality.
Includes unit tests demonstrating some examples of what the parser will and won't handle.
Example model:
class MyModel(models.Model):
file = RemovableFileField(upload_to='files', \
null=True, blank=True)
image = RemovableImageField(upload_to='images', \
null=True, blank=True)
A delete checkbox will be automatically rendered when using ModelForm or editing it using form_for_instance. Also, the filename or the image will be displayed below the form field. You can edit the render method of the DeleteCheckboxWidget or add one to RemovableFileFormWidget to customize the rendering.
UPDATE: 5. April 2009. Making it work with latest Django (thanks for the comments).
Based on [danjak's](http://www.djangosnippets.org/users/danjak/) [snippet](http://www.djangosnippets.org/snippets/99/) but updated to use ModelForms - so can easily handle generic CRUD operations.
A replacement create_update.py for use with ModelForm
create_object and update_project modified to handle newforms (including FileFields) with ModelForm - it also had delete_object as well for completeness.
In addition, it has some extras:
* extra_fields - this is a dict or callable that contains additional fields to be passed to the form, for example stuff that is in the session.
* on_success - callback called if form is valid and object created/updated, if this is not set the default behaviour is to send a redirect
* on_failure - callback called if form is invalid, the default is to redisplay the form.
Note that once newforms are finally done these functions are likely to be redundant, as generic views will be updated to use the newforms API, so use with caution!
For PyCon we have our crash messages go to a mailman group so that people working on the site would be aware of issues. This saved us many times. But sensitive information would some times come up such as login passwords and fields we did not want going on the list.
the solution was to mask these POST fields when an exception occurs and is being handled. This is simple drop-in code which will mask the values of POST arguments which contain keywords (such as 'password', 'protected', and 'private').
If you've ever wanted to dynamically lookup values in the template layer (e.g. `dictionary[bar]`), then you've probably realized/been told to do this in the python layer. The problem is then you often to build a huge 2-D list to hold all of that data.
These are two solutions to this problem: by using generators we can be lazy while still making it easy in the python layer. I'm going to write more documentation later, but here's a quick example:
from lazy_lookup import lazy_lookup_dict
def some_view(request):
users = User.objects.values('id', 'username')
articles = Article.objects.values('user', 'title', 'body')
articles = dict([(x['user'], x) for x in articles])
return render_to_response('some_template.html',
{'data': lazy_lookup_dict(users, key=lambda x: x['id'],
article=articles,
item_name='user')})
Then in the template layer you'd write something like:
{% for user_data in data %}
{{ user_data.user.username }}, {{ user_data.article.title }}
{% endfor %}
This middleware makes the admin error emails a lot more informative: you get the same HTML response that you get with `DEBUG=True`.
It uses the base class defined in [#638](http://www.djangosnippets.org/snippets/638/).
You will probably want to apply the patch for [#6748](http://code.djangoproject.com/ticket/6748) to help avoid slowdowns caused by unintentional database queries. As the ticket (and django-developers thread) notes, it isn't foolproof; you may still find this executing database queries.
Django EmailMessage class has no cc support and has bug in bcc support.
Core developers won't add cc support (see ticket http://code.djangoproject.com/ticket/5790),
and I don't want to wait half a year until they will realize they have a flaw that bcc recipients are sent to regular "to:" recipients and fix it.
So, if you want to use EmailMessage class right now, you'd better use FixedEmailMessage class. Class contract is the same, except for a new cc constructor argument.
**This code will throw deprecation warnings in newer Django checkouts - see the http://www.djangosnippets.org/snippets/773/ for an improved version that should work with the recent trunk.**
objects = MyModel.objects.all()
paginator = DiggPaginator(objects, 10, body=6, padding=2, page=7)
return render_to_response('template.html', {'paginator': paginator}
{% if paginator.has_next %}{# pagelink paginator.next #}{% endif %}
{% for page in paginator.page_range %}
{% if not page %} ...
{% else %}{# pagelink page #}
{% endif %}
{% endfor %}
http://blog.elsdoerfer.name/2008/03/06/yet-another-paginator-digg-style/
A MODPYTHON Apache Log Handler
This module provides a logging Handler class to a MODPYTHON Apache server. Python's standard [logging API](http://www.python.org/doc/2.5/lib/module-logging.html) explains how to [use a handler](http://www.python.org/doc/2.5/lib/multiple-destinations.html).
The handler, by default, writes entries to the Apache error_log using the standard Python logging API.
VIRTUAL HOSTS (Python 2.5)
This handler also supports Apache Virtual Hosts where the mp_server object is available. Then, it writes entries to the specific virtual-host server's error_log.
To get the mp_server object out of Django, you need the **log_extras()** function in your logging call (See the source comments).
This module must be bound to the Python logging API. Use a site_logging.py module to do that as this [related example](http://www.djangosnippets.org/snippets/960/) shows.
This snippet demonstrates the use of the SpecialOps patch ( [link here](http://hackermojo.com/mt-static/archives/2008/02/django-special-ops.html) )to the django 0.96 admin. Once you have the patch, adding actions like these is simple.
You can use the @admin_action decorator on model and manager methods to expose them inside the admin. For manager methods, the method should accept a list of IDs. For model methods, only self should be required.
ModelChoiceField allows you to use filtered queries to simplify your forms. This is great for adding objects but can fall down when you edit an existing object and the original query no longer contains the referenced field (e.g. I like to use an "active" field in several objects).
The fix is simply to include an extra param: Q(pk=object_id). You have to do this in the __init__ method to get the object_id.
A nice thing about this is that it works for ModelForms as well as custom Forms.
Have you ever felt the need to run multiple Django projects on the same memcached server? How about other cache backends? To scope the cache keys, you simply need to prefix. However, since a lot of Django's internals rely on `django.core.cache.cache`, you cannot easily replace it everywhere.
This will automatically upgrade the `django.core.cache.cache` object if `settings.CACHE_PREFIX` is set to a string and the Middleware contains `ScopeCacheMiddleware`.
A thread discussing the merging of this functionality into Django is available on [the dev mailing list](http://groups.google.com/group/django-developers/browse_thread/thread/d45edaafec56da2a).
However, (as of now) nowhere in the thread does anyone mention the reason why this sort of treatment is needed: Many of Django's internal caching helpers use `django.core.cache.cache`, and will then conflict if multiple sites run on the same cache stores.
Example Usage:
>>> from django.conf import settings
>>> from django.core.cache import cache
>>> from scoped_caching import prefix_cache_object
>>> settings.CACHE_PREFIX
'FOO_'
# Do this once a process (e.g. on import or Middleware)
>>> prefix_cache_object(settings.CACHE_PREFIX, cache)
>>> cache.set("pi", 3.14159)
>>> cache.get("pi")
3.14159
>>> cache.get("pi", use_global_namespace=True)
>>> cache.get("FOO_pi", use_global_namespace=True)
3.14159
>>> cache.set("FOO_e", 2.71828, use_global_namespace=True)
>>> cache.get("e")
2.71828
To Install: Simply add `ScopeCacheMiddleware` as a middleware and define `settings.CACHE_PREFIX` and enjoy!