You can use this function to change an admin option dynamically.
For example, you can add a custom callable to *list_display* based on request, or if the current user has required permissions, as in the example below:
class MyAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'other_field')
def changelist_view(self, request, extra_context=None):
if request.user.is_superuser:
add_dynamic_value(self, 'list_display', my_custom_callable)
return super(MyAdmin, self).changelist_view(request, extra_context)
Rather simple usage, modelforms/in the admin:
class CustomAdminForm(forms.ModelForm):
class Meta:
model = Something
widgets = {
'image': URLFileInput(default_exts=[".png", ".gif", ".jpg"]),
}
class SomethingAdmin(admin.ModelAdmin):
form = CustomAdminForm
admin.site.register(Something, SomethingAdmin)
Basically, this will pull the image from the URL instead of only pulling it from your harddrive for upload.
Also accepts optional default_exts argument which limits the file types. Defaults to images.
For example:
Last modified: {% localdt item.modified_utc %} ({% localtimesince time.modified_utc %})
Converts the input datetimes to the timezone specified by the localtz context variable (it can also be explicitly specified, and all those other sensible things).
Input UTC datetimes can be specified using either a datetime or a timestamp.
Provides `localdt`, `localtime`, `localdate` and `localtimesince`.
If you want to test for trivial error in your add and changelist admin views, use this snippet.
Save the snippet in admintests.py and put it anywhere in your pythonpath.
Put this code in your tests.py:
from django.test import TestCase
from admintest import adminviews_test
class TestAdminViews(TestCase):
def test_admin_views(self):
adminviews_test(self)
Look here: https://bitbucket.org/depaolim/optlock
The snippet of Marco De Paoli is much better than this one! :-)
=========================================================
If two users save same record, the second one will overwrite first one.
Use this snippet to achieve an optimistic locking, so the second user will get an exception.
Save the snippet in optlock.py and put it anywhere in your pythonpath.
**Do not put _version_opt_lock in readonly_fields** or the snippet will fail! (if you need to hide it, use jquery).
The snippet need in request.POST the original value of _version_opt_lock and if you make it a readonly field Django doesn't POST its value. When this [bug](https://code.djangoproject.com/ticket/11277) will be fixed it should be possible to use a hiddeninput widget.
models.py example:
...
import optlock
...
class YourModel(optlock.Model):
...
admin.py example:
...
import optlock
...
class YourModelAdmin(optlock.ModelAdmin):
...
That's it :-)
This filter will return data URI for given file, for more info go to:
[wikipedia](http://en.wikipedia.org/wiki/Data_URI_scheme)
Sample Usage:
`
<img src="{{ "/home/visgean/index.png"|dataURI }}">
`
will be filtered into:
`
<img src="data:image/png;base64,iVBORw0...">
`
This is good for small images.
This is a modification of Django 1.3's transaction.commit_on_success() decorator and context manager.
It's inspired by snippet [1343](http://djangosnippets.org/snippets/1343/) which unfortunately don't work in current Django neither as a context manager.
In my junior projects it works fine but I've not tested in critical projects yet! YMMV !
How it works: it simply counts the nesting level and does the real transaction enter/exit only on first call and last call respectively (code copied from Django's commit_on_success() ).
It use thread local storage to save the per-thread nesting level count safely.
To use it just put the code in a file (i.e. nested_commit_on_success.py) and import and use it exacly as normal commit_on_success(), both as decorator (@nested_commit_success) or context manager (with nested_commit_on_success(): ).
Any feedback is welcome!
This function takes a pattern with groups and replaces them with the given args and/or kwargs. Example:
IMPORTANT: this code is NOT to use replacing Django's reverse function. The example below is just to illustrate how it works.
For a given pattern '/docs/(\d+)/rev/(\w+)/', args=(123,'abc') and kwargs={}, returns '/docs/123/rev/abc/'.
For '/docs/(?P<id>\d+)/rev/(?P<rev>\w+)/', args=() and kwargs={'rev':'abc', 'id':123}, returns '/docs/123/rev/abc/' as well.
When both args and kwargs are given, raises a ValueError.
Django lacks support of MySQL's "tinyint" 8-bit-integer datatype. This snippet gives you a TinyIntegerField and a PositiveTinyIntegerField. Falls back Django's SmallIntegerField if a different database-engine is used
This snippet allows you to return back to the filtered change_list after clicking "Save" on a change form. Other snippets I've found don't seem to take into account clicking on "Save and add another" or "Save and continue"
Django's built-in {% regroup %} template tag is great, but sometimes, you need to pass in the attribute you want to group on instead of declaring the attribute when you define the tag.
{% dynamic_regroup %} is identical in function to {% regroup %}, except that it will attempt to resolve a context variable for the attribute you want to group by.
{% dynamic regroup %} is also backward compatible, so you can also hand in the attribute literal and it will work as expected.
See the end of the code for an example of usage.
**Description**
A filestorage system that
+ is whitlisted,
+ changes the file name and targeting directory to put the file in - with respect to (runtime) instance information.
+ replaces files if they exists with the same name.
Kudos to [jedie](http://djangosnippets.org/users/jedie/) - http://djangosnippets.org/snippets/977/
I needed to display formset into table and I didn´t like solution I have found. So I have written this simple tag you can use it in templates like this:
`
{% for row in formset|square_it:6 %}
<tr>
<td>
</td>
{% for form in row %}
<td>
{% for field in form %}
{{ field }}
{% endfor %}
</td>
{% endfor %}
`
This allows you to order the models on the index page of the administration site in a custom way.
This modification goes in the index method of django.contrib.admin.sites.AdminSite. I personally monkey patched it in where my models are loaded and registered with the admin site. Be careful that if you add new models you update the sorting dictionary, else you will get a key error. If no sorting is defined for an app, it will default to alphabetical order.
Note that you'll probably want to also insert this into the app_index function as well.
---
If you like my work, please check out my employer's site at 829llc.com
- Dan