A quick and dirty state machine inspired by the rails plugin, acts_as_state_machine.
When implementing this on a model, the model is expected to have a character field in the database called "state." Next, come up with a few states that a model can be in and initialize a machine object with those states. Now you need to define the way a model moves from one state to the next. You do this by calling the 'event' method on the machine object.
The first event argument defines the name of the method which will transition you to the next (to) state. The next argument is a dictionary defining what the current state must be in order to transition to the ending state. So, in the example, an Entry can transition from any state (the '*') to the draft state by calling entry.draft(). An entry can also transition from the 'draft' or 'hidden' state to the 'published' state which is enforced when calling entry.publish().
You can see what state a model object is in by calling <model_object>.state but sometimes it is more desirable to explicitly ask if a model object is in a particular state; this is done by the calling <model_object>.is_published() or <model_object>.is_draft(). All the code does is prefix "is_" to the "to" state which returns a True or False if the model is in that particular state.
Creates a filter for displaying calendars.
Passed value is a dict of dicts of arrays: that is, indexed by year, then by month. The list of month days is used to generate links in the format specified by the argument. If a particular day is *not* in the list, then no link will be generated and it will just display a number for that day.
**EXAMPLE**
`{{ calendar|calendar_table:"/schedules/calendar/[Y]-[m]-[d]/" }}`
This template extends the change form for the flatpages inside the admin interface to use [Yahoo! User Interface Library](http://developer.yahoo.com/yui/)'s [Rich Text Editor](http://developer.yahoo.com/yui/editor/).
It should be named `change_form.html` and be placed in the `admin/flatpages/flatpage/` directory of the project templates.
Watch out! Previous versions of this snippet (without the values list) were vulnerable to SQL injection attacks. The "correct" solution is probably to wait until [ticket 4102](http://code.djangoproject.com/ticket/4102) hits the trunk. But here's my temporary fix while we wait for that happy day.
Django's model.save() method is a PITA:
1. It does a SELECT first to see if the instance is already in the database.
2. It has additional database performance overhead because it writes all fields, not just the ones that have been changed.
3. It overwrites other model fields with data that may be out of date. This is a real problem in concurrent applications, like almost all web apps.
If you just want to update a field or two on a model instance which is already in the database, try this:
update_fields(user,
email='[email protected]',
is_staff=True,
last_login=datetime.now())
Or you can add it to your models (see below) and then do this:
user.update_fields(
email='[email protected]',
is_staff=True,
last_login=datetime.now())
To add it to your model, put it in a module called granular_update, then write this in your models.py:
import granular_update
class User(models.Model):
email = models.EmailField()
is_staff = models.BooleanField()
last_login = models.DateTimeField()
update_fields = granular_update.update_fields
Have you ever needed to customize permissions, for example, allow only some fields for editing by some group of users, display some fields as read-only, and some to hide completely?
FieldLevelPermissionsAdmin class does this for newforms-admin branch.
Not tested well yet (>100 LOC!).
You typically would like to use it this way:
class MyObjectAdmin(FieldLevelPermissionsAdmin):
def can_view_field(self, request, object, field_name):
"""
Boolean method, returning True if user allowed to view
field with name field_name.
user is stored in the request object,
object is None only if object does not exist yet
"""
...your code...
def can_change_field(self, request, object, field_name):
"""
Boolean method, returning True if user allowed to
change field with name field_name.
user is stored in the request object,
object is None only if object does not exist yet
"""
...your code...
def queryset(self, request):
"""
Method of ModelAdmin, override it if you want to change
list of objects visible by the current user.
"""
mgr = self.model._default_manager
if request.user.is_superuser:
return mgr.all()
filters = Q(creator=request.user)|Q(owner=request.user)
return mgr.filter(filters)
Usage:
{% if item|IN:list %}
The item is in the list.
{% endif %}
{% if customer.age|LE:18 %}
Go play out here.
{% endif %}
{% if product.price|add:delivery_cost|GT:balance %}
Insufficient funds.
{% endif %}
You've got the idea.
Special thanks to [guychi](http://www.djangosnippets.org/snippets/379/).
This is an example middleware that is highly inspired by how Symfony handles [i18n in URLs](http://www.symfony-project.com/book/trunk/13-I18n-and-L10n#Changing the Culture for a User). You basically set a (?P<dj_culture>[\w-]+) pattern in your URL and this middleware will determine the language to use for the i18n toolkit for Django.
It also removes the dj_culture parameter after dealing with it, so that you don't have to change all the views you want this middleware to work with.
Simple tag to enable easy parsing of inline code within a template. Usage: {% stylize "language" %}...language text...{% endstylize %}. Make sure to set the language for Pygments to parse as the first argument to the tag. You will also need to include a copy of the CSS that Pygments uses. The [Pygments](http://pygments.org/) library is required for this tag.
A merged version of the many jQuery autocomplete widgets.
See [1](http://php.scripts.psu.edu/rja171/widgets/autocomplete.php) and [2](http://www.dyve.net/jquery/?autocomplete) for more information.
You can use custom SQL statements with the existing database API by creating a subquery specified via the `tables` parameter of `extra`. (This has only been tested with MySQL and may not work with all database back-ends.)
Nutshell: Subclass this form with the required fields defined to automatically generate a form based on a model in a similar fashion to how form_for_model works, but in a way that tries to be a little easier if you want to customize the form. It handles updates and creations automatically as long as any database field requirements are met.
This is something I made while trying to understand newforms, and is my own attempt at something between the simplicity of a stock form_for_model form, and a full blown custom form. The proper way is to use a callback function to customize form_for_model, but that felt cumbersome so I did it my way :) It works for me, but I'm relatively new to both python and Django so please test yourself before trusting.
I use this script to export a group of models that I want to import later as initial data. It exports them as serialized json, which is perfect for importing later with the loaddata function in manage.py.
I use this script to keep track of the cache usage for various sites. It presently only supports memcached because that's all that I use, but leave a comment with patches for other systems and I'll add them.
You're looking at the most-bookmarked snippets on the site; if you'd like to help useful snippets show up here, sign up for an account and you'll get your own bookmarks list.