This adds a checkbox for each object and three buttons to a model's change list:
1. **Delete selected:** deletes the selected objects
2. **Delete shown: ** deletes all the visible objects. For example, if you perform a search or in any way filter the list, this button deletes only objects that were filtered.
3. **Delete all: ** Deletes all instances of the model, including those not shown (if looking at a filtered list).
The deletes perform no confirmation -- once you hit the buttons the models are **gone**, so maybe don't use (or add a confirmation screen) for really sensitive stuff.
* uses django oldforms-admin (ie 0.96)
* works fine if you include a search_fields list in the Admin class
* code for the view could probably be refactored a bit :)
Originally posted by [akaihola](http://www.djangosnippets.org/users/akaihola/) as [snippet #169](http://www.djangosnippets.org/snippets/169/). I just redid it as a filter.
Renders an select field with some optgroups. Some options can be outside the optgroup(s).
The options and labels should be in a tuple with ((label, choices),) where choices is a tuple ((key, value), (key2, value2)). If a label is null or blank, the options will not belong to an opt group.
I use these helper methods in my unit tests. They turn many simple getting-and-posting tests into one-liners. Definitely a work in progress, and I can't be the only person who has done this sort of thing -- comments are more than welcome.
A decorator similar to `cache_page`, which will cache any function for any amount of time using the Django cache API.
I use this to cache API calls to remote services like Flickr in my view, to prevent having to hit their servers on every request.
I posted a sample function which uses the [delicious API](http://www.djangosnippets.org/snippets/110/) in the function, also.
**Update**: It now also will put in a temporary 'in-process' variable (an instance of `MethodNotFinishedError`) in the cache while the function is processing. This will prevent the cache from calling the method again if it's still processing. This does not affect anything **unless you're using threads**.
This is a pretty straightforward bit of code for getting the most-commented objects of a particular model; just drop it into a custom manager for that model, and you should be good to go. Check the docstring for how to make it look at `Comment` instead of `FreeComment`.
This is, I think, a slightly cleaner implentation of what [snippet 31](/snippets/31/) is trying to do; by starting off with a dictionary containing the things we want to look for, and using a list comprehension to kill anything which comes out of the form as `None`, we can avoid some of the intermediate data structures the other snippet was using, and hopefully get better performance.
This is also quite a bit more maintainable, because supporting additional options now only requires adding a new key/value pair to `qdict`.
I knew that template in myght template system can receive some parameters just like a function. And I also want to implement this function in django template. So I finish a rough one, the code is pasted here. It just like include, but in order to distinguish with "include" tag, I call it "call". So you can use it:
{% call "some.html" %}
This way just like include tag, and the advanced way:
{% call "some.html" with "a" "b"|capfirst title="title1" %}
{% call "some.html" with "c" "d" title="title2" %}
So you can see, "call" tag can do like a python function, it can receive tuple parameters and key word parameters, just like the function:
def func(*args, **kwargs):pass
How to use it
===============
test_call.html
{% expr "limodou" as name %}
{% call "test/test_sub.html" with "a"|capfirst "b" title="title1" %}<br/>
{% call "test/test_sub.html" with "c" "d" title="title2" %}
expr is also a custom tag written by me. It'll calculate a python expression and save to result to a variable. In this case, the variable it "name".
test_sub.html
{% for i in args %}{{ i }}{% endfor %}
<h2>{{ title }}</h2>
<p>{{ name }}</p>
<h3>args</h3>
{{ args }}
<h3>kwargs</h3>
{{ kwargs }}
And you also can see, call tag will auto create args and kwargs context variables.
I hope this will be some useful.
I found model definitions with large number of fields with long help_text unreadable and feel that help_text doesn't really belong to field definition. With this snippet help_text attributes can live outside field definitions in inner HelpText class so field definitions become shorter and more readable.
Usage:
from django.db import models
import readable_models
class MyModel(models.Model):
__metaclass__ = readable_models.ModelBase
name = models.CharField('Name', max_length=30)
address = models.CharField('Address', max_length=255)
# ... long list of fields
class HelpText:
name = 'The name ...'
address = 'Example: <very verbose example is here>'
This avoids the frustrating step of having to set up a new admin user every time you re-initialize your database.
Put this in any `models` module. In this example I use `common.models`.
Adapted from http://stackoverflow.com/questions/1466827/
This jQuery javascript enables dynamic add/delete of rows in tabular inlines. It adds a "+" icon at the bottom of the inline to allow addition of new rows, and replaces the default delete checkbox with a "x" icon for deletion, giving you the possibility to add/delete rows instantly without reloading the page.
In addition, it gives you drag-n-drop ordering functionality with a named position model field using jQuery UI Sortable.
**Usage (see below for example):**
Just include the javascript on your admin page, together with jQuery, and it'll automatically affect all tabular inlines. Optionally, also include jQuery UI Sortable and an Integer field in your inline model named "position" (or whatever you set "position_field" to), which will automatically hide the position field and enable drag-n-drop sorting.
**Developed for:**
* jQuery 1.3.2
* jQuery UI 1.7.1
* Django trunk (tested in Django v1.0.2)
* (Might work with other versions with or without adjustments, but not tested)
**Settings (in top of javascript):**
* "position_field" is the name of an integer model field that is used for ordering the inline model. If left empty or not found, the drag-n-drop functionality is dropped. Defaults to "position".
* "add_link_html" for custom look of "add"-buttons. Defaults to Django's built-in "+" image icon.
* "delete_link_html" for custom look of "delete"-buttons. Defaults to Django's built-in "x" image icon.
**Use example: **
*admin.py:*
class NameInline(admin.TabularInline):
model = Name
extra = 1
class PersonAdmin(admin.ModelAdmin):
inlines = [NameInline]
class Media:
js = ['js/jquery-1.3.2.min.js', 'js/ui/ui.core.js',
'js/ui/ui.sortable.js', 'js/dynamic_inlines_with_sort.js',]
css = { 'all' : ['css/dynamic_inlines_with_sort.css'], }
admin.site.register(Person, PersonAdmin)
*models.py:*
class Person(models.Model):
year_born = models.PositiveIntegerField(_('year born'), null=True, blank=True)
class Name(models.Model):
profile = models.ForeignKey(Profile, verbose_name=_('profile'))
position = models.PositiveIntegerField(_('position'), default=0)
name = models.CharField(_('name'), max_length=100)
class Meta:
ordering = ('position',)
*dynamic_inlines_with_sort.css:*
/* To make row height of saved items same as others */
.inline-group .tabular tr.has_original td { padding-top:0.5em; }
.inline-group .tabular tr.has_original td.original p { display:none; }
Please post bugs in comments.
Convert numbers from base 10 integers to base X strings and back again.
Sample usage:
>>> base20 = BaseConverter('0123456789abcdefghij')
>>> base20.from_decimal(1234)
'31e'
>>> base20.to_decimal('31e')
1234
This snippet display a human readable date diff. You give it the your date in parameter and the diff with datetime.datetime.now() is returned. The diff must be positive to be more accurate (future dates are not supported)
Usage:
{{ status.created_at|date_diff }}
Will give something like:
less than 1 minute ago
13 minutes ago
1 hour ago
etc.
Based on [Fuzzy Date Diff Template Filter](http://www.djangosnippets.org/snippets/1347/)
Allows you to include globs of IP addresses in your INTERNAL_IPS. It's shell-style glob syntax (the [fnmatch module](http://docs.python.org/library/fnmatch.html)).
This should be helpful with the [Debug Toolbar](http://github.com/robhudson/django-debug-toolbar/tree/master), among other things.
Like [#1362](http://www.djangosnippets.org/snippets/1362/), but with no external dependencies.
You're looking at the top-rated snippets currently on the site; if you'd like to contribute, sign up for an account and you'll be able to rate any snippet you see.