This is what I use to send simple status emails from my sites. Instead of a django.core.mail.send_mail call, which can take an irrritatingly, nondeterministically long time to return (regardless of error state), you can stow the emails in the database and rely on a separate interpreter process send them off (using a per-minute cron job or what have you). You then also have a record of everything you've sent via email from your code without having to configure your outbound SMTP server to store them or anything like that.
Usage notes are in the docstring; share and enjoy.
**autoprefixed** is a decorator for Form classes that simplifies prefix handling by storing it in a hidden field. Thus when the form is posted, the prefix can be extracted from the posted data instead of having to pass it explicitly when instantiating the form.
django-adminwidgetswap
===============
adminwidgetswap is used for dynamically swapping out widgets from django's generated admin.
This allows applications to be packaged generically without the need for WYSIWYG dependencies editors- giving the application consumer the freedom to chose admin widgets without modifying original app source.
Author
======
[David Davis](http://www.davisd.com)
(http://www.davisd.com)
[dynamically change django admin widets at runtime (django-adminwidgetswap) blog post](http://www.davisd.com/blog/2010/04/17/dynamically-change-django-admin-widgets-at-runtime/)
Usage
===============
To change a widget in django's admin, just put adminwidgetswap.py on the python path, import adminwidgetswap.py and use:
adminwidgetswap.swap_model_field(model, field, widget)
...to change a widget for a direct model admin's field
---
adminwidgetswap.swap_model_inline_field(model, field, widget)
...to change widgets for inlines of a specific model and field
---
adminwidgetswap.swap_model_and_inline_fields(model, field, widget)
...to change both the widget for the direct model admin's field as well as all inline usages for the model and field
---
I usually have a project-level application called website, and I put this initialization code inside the website app's __init__.py
Usage - parameters
===============
model is the Model class
(eg. models.GalleryImage)
field is the field name you're looking to swap
(eg. 'image')
widget is the widget you're going to swap for
(eg. widgetlibrary.ThumbnailWidget())
This snippet adds simple partial support to your templates. You can pass data to the partial, and use it as you would in a regular template. It is different from Django's {% include %}, because it allows you to pass a custom variable (context), instead of reusing the same context for the included template. This decouples the templates from each other and allows for their greater reuse.
The attached code needs to go into templatetags folder underneath your project. The usage is pretty simple - {% load ... %} the tag library, and use {% partial_template template-name data %} in your template. This will result in template passed as template-name to be loaded from your regular template folders.
The variables are passed in a with compatiable syntax, eg.
VAR as NAME and VAR as NAME
No limitations on the number of variables passed.
I did not like the idea of having to load fixtures by creating a huge initial_data.json file. I also did not want to store my initial data in a bunch of <modelname>.sql files.
Django has post_syncdb signal which fires when model(s) for an application are installed, but I needed something that would run only *once* at the end of syncdb command, at least after all of the models are installed, and here's what I've come up with. The code basically checks if the current callback is for the last app in your INSTALLED_APPS, and if so, executes some fixture loading code.
Forces Django not to translate built in template tags and filters.
If you have a multi-lingual site but certain parts of it are not all translated, you can use this snippet to force Django to bypass translation on all template tags and filters so things like dates aren't randomly translated whilst everything else is not.
For example:
`{% notrans %}{{download.doc|filesizeformat}}{% endnotrans %}`
This snippet including the filesizeformat template tag would not be translated.
Mega thanks goes out to Dan Fairs for all his help on this!
This is an example how to create a wrapping function that can read all incoming arguments, do something with them and then call the original function. This pattern works well with generic views.
Note that wrapper function accepts arguments in both ways: as a list of unnamed arguments and as a list of keyword-value pairs.
A real-world example:
def published_object_list(request, *args, **kwargs):
arg_names = object_list.func_code.co_varnames
params = dict(zip(arg_names, args))
params.update(kwargs)
params['queryset'] = params['queryset'].filter(is_published=True)
if request.is_ajax():
params['template_name'] = "ajax/" + params['template_name']
return object_list(request, **params)
Middleware to set "sessionid" (ou your session cookie) with httponly (see ["Django bug report"](http://code.djangoproject.com/ticket/3304)). To work, you need put it before "SessionMiddleware"
Inspired by this [terse blog post](http://www.ghastlyfop.com/blog/2008/12/strip-html-tags-from-string-python.html).
This filter was designed to simplify the stripping out of all (x)html in a given template var, while preserving some meta information from anchor, and image tags.
Why is this even useful? If you have pre-assembled portions of templates, or model fields containing html, that you want to use to populate a *search index* like [django-haystack](http://haystacksearch.org/) you can safely discard all the markup, while keeping the text that should be still searchable. Alt text, and title attributes are worth keeping!
**Disclaimer**
This is proof of concept snippet, It can not be considered as best practice. Seems like it's better to store (key => value) in sepetare model with 'key' and 'value' fields.
**Example**
You can assign any dict to model field that can be dumped/serialized with Django json encoder/decoder. Data is saved as TextField in database, empty dict is saved as empty text. Tested with Django 1.2beta.
import DictionaryField
class UserData(models.Model):
user = models.ForeignKey(User)
meta = DictionaryField(blank=True)
There are similar snippets: [JSONField 1](http://www.djangosnippets.org/snippets/377/) or [JSONField 2](http://www.djangosnippets.org/snippets/1478/).