Makes sure the value a user entered into a a text-based field is automatically trimmed during form cleaning / validation.
The 'field' parameter is expected to be a newforms.fields.Field _instance_.Only modifies str and unicode descending values, and passes everything else on untouched.
Example:
form = form_for_model(Person)
make_trimming(form.fields['name'])
Adds a filter input above a select widget that allows live-filtering on the client-side (no ajax) in Firefox.
Example:
make_fields_searchable(ModelItemForm, {
'publisher': {'set_size': 8}, 'developer': {'set_size': 8}, 'genre': {}, 'platform': {}
})
The solution is based on [dballanc's snippet](http://www.djangosnippets.org/snippets/420/).
Can easily be combined with any of the [SQL tracing solutions](http://www.djangosnippets.org/tags/debug/).
You might want to run a separate logging server and redirect your logs there. Please refer to the [logging reference manual](http://docs.python.org/lib/module-logging.html).
The django debug screens are great, but only when you can see them. Trying to debug javascript/ajax calls can be kind of a pain. This just a copy/paste of some code in django's internals stuck in a middleware so that exceptions also print to the dev server console.
Simple middelware that listens for redirect responses, store the request's query log in the session when it finds one, and starts the next request's log off with those queries from before the redirect.
Make sure we don't create an infinite loop with a self-referencing foreign key.
Many times I have needed category models that reference themselves, providing a flexible way to make children categories, grandchildren categories, etc. If you chain the slugs (or even ids) there's a chance you could end up with an infinite loop.
Assumes a required, unique slug field ('slug') and an optional self-referencing foreign key
('parent'). All_data doesn't give you the object's ID, so we will find it via the unique slug.
If either is not present we pass -- if there's no parent chosen it's not a problem, and if there
is no slug present the submission will fail on that validation instead. It is worth noting that
if the user changes the slug field on submission AND picks a bad parent it will not be caught.
Infinite loop cases:
1. A references A
2. A tries to reference B, which is currently referencing A
Replaces <code> blocks with syntax highlighted code. Use CSS to actually get the colours you want, look at pygments documentation for extracting css for various styles.
This snippet has the advantage of falling back on <pre> if anything goes wrong, and attempting to guess the syntax of code, falling back on python.
Peeping middleware, that replaces active user to another one
for current http request. Admin permissions required to activate,
so you can place this snippet even on the production server.
Very useful for debugging purposes. Wish it to be part of Django.
How to use:
Put this middleware after all other middlewares in the list.
Then just add ?as_user=username
or &as_user=username to the url,
where username is the name of user whose views you want to see.
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/).
If you ever have a need to display something like:
"last update 5 days ago"
"user logged in 2 mins ago"
you can use this script to determine how long ago a timestamp is versus now().
I tried to use [Joshua's](http://www.djangosnippets.org/users/joshua/) nice and very useful [getattr template filter (#38)](http://www.djangosnippets.org/snippets/38/), but ran into a few problems.
I used it on objects outside of my control (admin internals, coughcough) and on some of them the code didn't catch the resulting exceptions. So I improved the error handling a bit.
Furthermore, the code now also returns the *value of a callable* instead of the callable *itself* (last 4 lines).
Looking at my code though, it can certainly be improved further.
Dada una fecha_origen, incrementa N dias a partir de esa fecha ignorando sábados y domingos.
Increments a date by n days without counting weekends. Just working days.
If you're like me, you've got a models with a lot of fields/foreignkeys and often only want to edit a portion of the model in a form. Add this method to your custom form class and use it in place of the save() method.
I wanted to have the possibility to use a wiki-like markup style in my flatpages for various purposes (embedding images, quoting, etc.)
After a few dead ends I came up with this, which is quite nice I think.
> It basically takes a named tag, loads the corresponding template, passes in all arguments, renders the template and replaces the named tag with the result.
*The markup looks like this:*
> [[example:value to pass|option1=somevalue option2=values can have spaces too! without having to put them in quotes option3=some other value]]
*This results in:*
* Filter tries to load wiki/wiki_example.html
* If it is loaded, it passes an WikiElement containing the value and the options to the template, renders it and replaces the tag with the rendered template
*In the "wiki/wiki_example.html" template you can use it like this:*
{{param.value}}
{{param.opts.option1}}
Or loop over param.opts.iteritems.