- Choices are saved as the key integers.
- Admin will show the correct translation in forms.
- You can reuse the make_choices function for other choices fields.
- Bad side: bin/make_messages.py won't get the choices values automatically, you have to add them in the .po's by hand.
This adds a checkbox in the admin site that removes the reference to a file uploaded via a FileField (or ImageField). It does not delete the actual file.
I needed to be able to synchronize my LDAP users and groups to the Django database. This may not be as efficient as some might like but it works like a charm. It returns a list of messages that I pipe into request.user.messages in my template.
** Help me get better! If you vote (either way) please leave a comment if you have time and say what was good or bad. I appreciate any and all feedback. Thanks! **
I keep finding places in my apps where I need an isolated snippet of text that can periodically be changed from the admin interface. Most often it's html but sometimes it's text, javascript, or css.
Use it like so:
(Assuming this snippet lives in snippy_snip/models.py and there is a snippet named "Welcome Message" in the database)
from snippy_snip.models import snip
msg = snip("Welcome Message")
Or, you might populate a parameter hash for a template:
def showpage(request):
params = {
'welcome': snip('Welcome Message'),
'video1': snip('Video 1'),
'NavHeader': snip('Nav.SectionHeader'),
}
return render_to_response("main.html", params)
For clarity, *params* might look something like this:
welcome -> "Welcome to our site. Please use the menu on the left..."
video1 - > a YouTube snippet
NavHeader -> Some HTML which comprises the top of a navigation menu.
This is a very simple bit of code but I've found it very useful. It isn't intended for instant changes... Your snippets will cache like anything else, which may cause confusion if you expect immediate changes. And it's probably not great for a high traffic site, but for my moderate traffic sites and workgroup apps I've found it useful.
(This code was created for 0.96, but I'm working to bring it into alignment with the latest svn version of Django, see comments.)
Template tag for displaying a list of arbitrary models. Useful for life-stream kind of pages that display blog entries, links, photos etc ordered by date. [Example](http://bjornkri.com)
**Usage:** something like:
{% for object in object_list %}
{% display_excerpt object %}
{% endfor %}
Will look for *app/model_excerpt.html* by default, and fall back on a generic *display_excerpt.html*, or returns the object's string representation as a last fallback.
*display_excerpt.html* might look something like:
<a href="{{ object.get_absolute_url }}">{{ object }}</a>
Any model you throw at it should have a *get_absolute_url* and a string representation of some sort, so this gives you the bare minimum of a title and a link to a detail page.
*display_excerpt* takes an optional argument to set the template suffix. This might be handy for generating different formatting for feeds, for instance:
{% for object in object_list %}
{% display_excerpt object "feed" %}
{% endfor %}
This will look for app/model_feed.html to render the object.
Got lots of help from mattmcc on #django for this one, thanks!
Based on [this snippet](http://www.djangosnippets.org/snippets/660/), adapted to split a list into *n* number of sublists, e.g. split a list of results into three evenly-divided sublists to enable display of the results in three columns on one page with CSS.
Tag: `{% list_to_columns your_list as new_list number_of_columns %}`
The split_seq solution comes from a comment by Sebastian Hempel on [this post](http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425397).
More info [here](http://herself.movielady.net/2008/07/16/split-list-to-columns-django-template-tag/).
Often times I want to be able to interchangeably pass either literal strings or context variables to a custom templatetag. This function first checks a string for the existence of surrounding quotes and uses the string inside. If the string didn't explicitly use quotes it checks to see if it can resolve the string as a context variable. As a fallback the function will simply return the full string.
Example:
{% get_latest_by_tag 'django' %}
{% get_latest_by_tag object.tag %}
This is a ModelForms-based rewrite of the create_object and update_object generic views, with a few added features. The views now accept a "form_class" argument optionally in place of the "model" argument, so you can create and tweak your own ModelForm to pass in. They also accept a "pre_save" callback that can make any additional changes to the created or updated instance (based on request.user, for instance) before it is saved to the DB.
Usage: just save the code in a file anywhere on the PythonPath and use the create_object and update_object functions as views in your urls.py.
**This is a model field for managing user-specified positions.**
Usage
=====
Add a `PositionField` to your model; that's just about it.
If you want to work with all instances of the model as a single collection, there's nothing else required. In order to create collections based on another field in the model (a `ForeignKey`, for example), set `unique_for_field` to the name of the field.
It's probably also a good idea to wrap the `save` method of your model in a transaction since it will trigger another query to reorder the other members of the collection.
Here's a simple example:
from django.db import models, transaction
from positions.fields import PositionField
class List(models.Model):
name = models.CharField(max_length=50)
class Item(models.Model):
list = models.ForeignKey(List, db_index=True)
name = models.CharField(max_length=50)
position = PositionField(unique_for_field='list')
# not required, but probably a good idea
save = transaction.commit_on_success(models.Model.save)
Indices
-------
In general, the value assigned to a `PositionField` will be handled like a list index, to include negative values. Setting the position to `-2` will cause the item to be moved to the second position from the end of the collection -- unless, of course, the collection has fewer than two elements.
Behavior varies from standard list indices when values greater than or less than the maximum or minimum positions are used. In those cases, the value is handled as being the same as the maximum or minimum position, respectively. `None` is also a special case that will cause an item to be moved to the last position in its collection.
Limitations
===========
* Unique constraints can't be applied to `PositionField` because they break the ability to update other items in a collection all at once. This one was a bit painful, because setting the constraint is probably the right thing to do from a database consistency perspective, but the overhead in additional queries was too much to bear.
* After a position has been updated, other members of the collection are updated using a single SQL `UPDATE` statement, this means the `save` method of the other instances won't be called.
More
===
More information, including an example app and tests, is available on [Google Code](http://code.google.com/p/django-positions/).
**Update**:
[Django AdMob](http://github.com/johnboxall/django_admob/tree/master) pluggable app on github.
Given a Django ``request`` object and dict of admob parameters returns a Admob ad.
If no ad can be retrieved displays a one pixel Admob tracker image.
For the future:
* Make a template tag for this?
* Filter out other unneeded META parameters for the admob_post dict?
A [common pattern in Django](http://code.djangoproject.com/wiki/UsingMarkup) is to create a TextField intended for Markdown text (i.e. description) and a companion non-editable TextField for storing the HTML version (i.e. description_html), so the Markdown converter need not be run for every page view.
This snippet is a custom field which encapsulates this pattern in a single field which can automatically create and update its companion HTML field.
Usage:
class MyModel(models.Model):
description = MarkdownTextField()