This sample site_logging.py module uses the [MODPYTHON Logging snippet](http://www.djangosnippets.org/snippets/627/). It assigns the ApacheLogHandler class to the main logging object, when Django is run inside MODPYTHON.
You must have the MODPYTHON Logging snippet, and name it modpython_logging.py for this to work. Apache will write to virtual host-specific logs only with Python 2.5.
Users are encouraged to change the two logging settings.
Log Level: handler.setLevel(logging.WARNING)
Log Format: logging.Formatter(...)
This filter converts HTML to nicely-formatted text using the text-browser W3M. I use this for constructing e-mail bodies, since it means I don't have to have two templates, one HTML and one plain-text, for each detailed e-mail I want to send. Besides the obvious maintenance benefits, this is nice because Django's templating system isn't well-suited to plain-text where whitespace and line-breaks are significant.
I chose W3M because it renders tables nicely and can take in HTML from STDIN (which Lynx can't do). An alternative is ELinks; to use it, change "cmd" to the following: `elinks -force-html -stdin -dump -no-home`
Here is a class decorator that allows not to bother with stripping leading and trailing white space from user input provided via forms. This could be a temporary solution for an issue addressed in the ticket [#6362](http://code.djangoproject.com/ticket/6362).
The documentation is provided in the form of doctest. The decorator works with `ModelForm`'s just as well as with ordinary forms.
Note however that this is not a 100% panacea. Your models still could become malformed if theirs data is obtained from another source, not forms.
A filter to resize a ImageField on demand, a use case could be:
<img src="{{ object.image.url }}" alt="original image">
<img src="{{ object.image|thumbnail }}" alt="image resized to default 104x104 format">
<img src="{{ object.image|thumbnail:200x300 }}" alt="image resized to 200x300">
Original http://www.djangosnippets.org/snippets/192/
The original USPhoneNumberField only validates xxx-xxx-xxxx values.
This field validates...
> (xxx) xxx xxxx
> xxx-xxx-xxxx
> (xxx)-xxx-xxxx
> many others.
**Explanation of the regular expression:**
1. Accepts either (xxx) or xxx at the start of the value.
2. Allows for any amount of dashes and spaces (including none) before the next set of digits.
3. Accepts 3 digits
4. Allows for any amount of dashes and spaces (including none) before the next set of digits.
5. Accepts 4 digits, finishing the value.
This field saves in the same format that the original USPhoneNumberField does (xxx-xxx-xxxx).
Enjoy!
Uses JSMin. Python version available from
[http://www.crockford.com/javascript/jsmin.py.txt](http://www.crockford.com/javascript/jsmin.py.txt)
Provides template tags to minify JavaScript on the fly.
`{% minifyjs %}[code]{% endminifyjs %}`
Refactors two similar django template files to use `{% block %}` tags.
Takes two template files, where one is a modified version of the other, and looks for differences and similiarities between the two.
It then generates refactored (and renamed) versions of each file and a third 'base' file, adding an `{% extends %}` tag as appropriate.
Block tags are named with matching numbers in all 3 files, making it easy to do a search and replace with more meaningful labels.
`sample_data_in_base` controls whether or not the content from file 1 is copied into place in the base file as an example.
Problems: it doesn't identify open `{% for %}` or `{% if %}` tags, so this needs some manual fixing (moving the `{% endfor %}` and `{% endif %}` tags into the proper blocks). It doesn't add the correct path for the `{% extends %}` tag either (ie. `"app/base.html"`). `collapse_whitespace` is not working at all.
Django administration provides three buttons for submitting the currently edited object. Each of them has a unique name and depending on the name that is sent to the server, the specific action is performed. I see this as an ugly solution and prefer to have a choice field in the form which would render as submit buttons with different values. Then the values would be checked instead of the names. Therefore, I created the `MultipleSubmitButton` widget. When `<input type="submit" value="Go" />` is used, the value sent to the server always matches the text on the button, but if `<button type="submit" value="go">Go</button>`, the value and the human representation might differ.
To use the `MultipleSubmitButton` widget, pass it to the widget parameter of a `ChoiceField` like this:
SUBMIT_CHOICES = (
('save', _("Save")),
('save-add', _("Save and Add Another")),
)
class TestForm(forms.Form):
do = forms.ChoiceField(
widget=MultipleSubmitButton,
choices=SUBMIT_CHOICES,
)
When you print `{{ form.do }}` in the template, the following HTML will be rendered:
<ul>
<li><button type="submit" name="do" value="save">Save</button></li>
<li><button type="submit" name="do" value="save-add">Save and Add Another</button></li>
</ul>
When you submit this form and check the validity of it, `form.cleaned_data['do']` will return "save" or "save-add" depending on the submit button clicked.
When you're using Django model inheritance, sometimes you want to be able to get objects of the base class that aren't instances of any of the subclasses. You might expect the obvious way of doing this, `SuperModel.objects.filter(submodel__isnull=True)`, to work, but unfortunately it doesn't. (Neither does `SuperModel.objects.filter(submodel__supermodel_ptr=None)`, or any other convoluted way I could think of doing it.) Here's a nicer approach for doing this.
[The blog entry is here.](http://sciyoshi.com/blog/2008/aug/07/custom-django-manager-excludes-subclasses/)
The venerable CustomImageField, invented by [Scott Barnham](http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/) and rejiggered for newforms-admin by [jamstooks](http://pandemoniumillusion.wordpress.com/2008/08/06/django-imagefield-and-filefield-dynamic-upload-path-in-newforms-admin/#comments).
This here is a stab at a [post-Signals-refactor](http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges#Signalrefactoring) version. Seems to do 'er.
Note: This should be pointless once [fs-refactor](http://code.djangoproject.com/ticket/5361) lands.
In the past, whenever I had a script that I wanted to properly configure the settings for, I would use something like the following idiom at the top of the script:
import sys, os; dirname = os.path.dirname
# sys.path.insert(0, dirname(dirname(__file__)))
sys.path.insert(0, dirname(__file__))
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
Notice that this is a relative setting to `__file__` variable in the script. The djangopath function is an attempt to do away with the above such that I can now write the following:
from lib import djangopath; djangopath(up=2, settings='myapp.settings')
This seems to work for me, but it assumes that you are packaging your script inside your projects/apps. If they are elsewhere then you may need to resort to another method (e.g. absolute paths, etc.)
AK
Special thanks to all the authors of djangosnippets. It's my first contribution.
Maybe the method **online_users** could be better, but for now it's working for me.
Best Regards from Bolivia.
Best practice based on [YSlow recommendations](http://developer.yahoo.com/yslow/), add the following to your Apache config for your media directory.
<Directory /home/.../site_media/>
...
FileETag None
ExpiresActive on
ExpiresDefault "access plus 10 years"
AddOutputFilterByType DEFLATE text/css application/x-javascript
</Directory`
Make sure to enable mod_deflate and mod_expires.
This middleware refreshes the session before it expires to avoid dropping the session of an active (but read-only) user. By default it refreshes the session after half the expiry time has elapsed.
(This middleware does nothing for browser-length sessions.)
Requires [GitPython](http://gitorious.org/projects/git-python).
Grabs the most recent commits to a Git repository, as defined in `settings.py`. Inspired by [Simon Willison](http://simonwillison.net)'s [about page](http://simonwillison.net/about/).
**Example:**
{% get_recent_commits 10 as commits %}
<ul>
{% for commit in commits reversed %}
<li>{{ commit.commited_date }} - {{ commit.message }}</li>
{% endfor %}
</ul>