Login

All snippets written in Python

Snippet List

Dynamically insert or append a value to an admin option, e.g. list_display or list_filter

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)

  • admin
  • list_display
  • list_filter
Read More

Load File From URL Widget

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.

  • imagefield
  • filefield
  • urlfield
Read More

Template tags for localizing UTC times with pytz

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`.

  • timezone
  • pytz
  • timezones
Read More

Automatic testing of add and changelist admin views

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)

  • admin
  • test
  • automatic test
Read More

Optimistic locking in Admin

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 :-)

  • admin
  • locking
  • optimistic locking
Read More

filter for simplifying creating data URI´s

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.

  • filter
  • mime
  • uri
  • data URI
Read More

nested transactions context manager and decorator

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!

  • decorator
  • nested
  • transaction
  • contextmanager
Read More

Replacing pattern groups by values

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.

  • regex
  • reverse
Read More

TinyIntegerField

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

  • model
  • db
  • 8-bit-integer
  • MySQL
  • IntegerField
  • tiny-integer
Read More

Return to change_list with filter after change

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"

  • filter
  • admin
  • change_list
Read More

Dynamic Regroup Template Tag

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.

  • templatetag
  • dynamic
  • regroup
Read More

Whitelisted overwriting FileSystemStorage

**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/

  • forms
  • filefield
  • whitelist
  • filestorage
  • overwrite
  • file-extension
Read More

grouper tag

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 %} `

  • template
  • tag
  • templatetag
  • formset
Read More

Admin Model Sorting

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

  • models
  • admin
  • sort
  • sorting
  • app-models
Read More

2955 snippets posted so far.