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.
I come up with this short cut of saving data from newforms to a model, for newforms that contains attributes from several models or some attributes that doesn't found in a model attributes
You can switch boolean fields in the admin without editing objects
Usage:
`
class News(models.Model):
# ...
pub = models.BooleanField(_('publication'),default=True)
# ...
pub_switch = boolean_switch(pub)
class Admin:
list_display = ('id', 'pub_switch')
`
Thanks for [svetlyak](http://www.djangosnippets.org/snippets/398/).
**Javascript merging and compression templatetag**
One of the most important things for improving web performance is to reduce the number of HTTP requests. This is a templatetag that merges several javascript files (compressing its code) into only one javascript.
It checks if this merged file is up to date, comparing modification time with the other javascripts to merge.
Usage:
{% load jsmerge %}
{% jsmerge mergedfile js/file1.js js/file2.js js/file3.js %}
The previous code will:
1. Search in `settings.MEDIA_ROOT` for all files passed by parameter.
2. Create a `/path/to/media_root/mergedfile.js` (if it doesn't exist or it's not up to date). This file is a merging plus compression of all javascripts.
3. Return this HTML fragment: `<script type="text/javascript" src="/media_url/mergedfile.js"></script>`
A URL field specifically for images, which can validate details about the filesize, dimensions and format of an image at a given URL, without having to read the entire image into memory.
Requires [Python Imaging Library](http://www.pythonware.com/library/pil/).
*4th October, 2008* - updated for 1.0 compatibility.