Login

All snippets written in Python

2956 snippets

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

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

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

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

TaskViewMixin, fires off a task and polls until completion

TaskViewMixin can be mixed in with a Class Based view and handles the scheduling and polling of a task. During task execution, a waiting page is rendered that should refresh itself. Once the task is complete, the view may then render a success page and can collect the payload of the task for rendering the result.

  • asynchronous
  • class-based-views
  • celery
Read More

Django load global fixtures test helper

This lets you load global fixtures from a directory you set as `FIXTURES_ROOT` in your settings.py. For example, setting `FIXTURES_ROOT` to `/path/to/myproject/fixtures/` I tend to like to keep fixtures that should be loaded when a new instance of a site is deployed, but not auto-loaded (so they won't rewrite any data that comes after), in a project-level fixtures directory like this. Sometimes these fixtures can be useful in your test suites, so this is a convenient way to load them. Usage: `load_global_fixtures('sites.json', 'contacts.json')` `load_global_fixtures('sites.json', 'contacts.json', fixtures_root='/some/other/path', verbosity=1)`

  • fixtures
  • tests
  • helper
Read More
Author: vaz
  • 1
  • 1

Transparently encrypt ORM fields using OpenSSL (via M2Crypto)

Sometimes you need to store information that the server needs in unencrypted form (e.g. OAuth keys and secrets), but you don't really want to leave it lying around in the open on your server. This snippet lets you split that information into two parts: * a securing passphrase, stored in the Django settings file (or at least made available via that namespace) * the actual secret information, stored in the ORM database Obviously, this isn't as secure as using a full blown key management system, but it's still a significant step up from storing the OAuth keys directly in the settings file or the database. Note also that these fields will be displayed unencrypted in the admin view unless you add something like the following to ``admin.py``: from django.contrib import admin from django import forms from myapp.fields import EncryptedCharField class MyAppAdmin(admin.ModelAdmin): formfield_overrides = { EncryptedCharField: {'widget': forms.PasswordInput(render_value=False)}, } admin.site.register(PulpServer, PulpServerAdmin) If Django ever acquires a proper binary data type in the default ORM then the base64 encoding part could be skipped. This snippet is designed to be compatible with the use of the South database migration tool *without* exposing the passphrase used to encrypt the fields in the migration scripts. (A migration tool like South also allows you to handle the process of *changing* the passphrase, by writing a data migration script that decrypts the data with the old passphrase then writes it back using the new one). Any tips on getting rid of the current ugly prefix hack that handles the difference between deserialising unencrypted strings and decrypting the values stored in the database would be appreciated! Sources of inspiration: [AES encryption with M2Crypto](http://passingcuriosity.com/2009/aes-encryption-in-python-with-m2crypto/) [EncryptedField snippet](http://djangosnippets.org/snippets/1095/) (helped me improve several Django-specific details)

  • fields
  • encryption
Read More

Prettify HTML5 middleware

Slightly updated version of http://djangosnippets.org/snippets/172/ . Supports new HTML5 tags (even though tidy doesn't).

  • middleware
  • tidy
  • standard
  • html5
Read More

Read only form & model field

These decorators can be used to make some model/form fields readonly. **Sample usage:** # Use this decorator on form with readonly fields.` @modelform_with_readonly_fields` class FooAdminForm(forms.ModelForm):` ... # This decorator shoud be used to protect selected fields ` # from modification after initial save.` @has_readonly_fields` class Foo(models.Model):` read_only_fields = ('name', )` ... **Result** will be the same as shown in this post: [Readonly field](http://stackoverflow.com/questions/324477/in-a-django-form-how-to-make-a-field-readonly-or-disabled-so-that-it-cannot-be/1424453#1424453) and [Readonly model field](http://www.djangozen.com/blog/read-only-fields-in-models)

  • forms
  • model
  • field
  • readonly
Read More

Loading templates by app path

Loading templates by path app.template_name -> app/templates/template_name.html app.subdir.template_name -> app/templates/subdir/template_name.html Usage: append in settings.TEMPLATE_LOADERS and using render_to('app.index', context)

  • template
  • loader
Read More

format_thousands

Template filter to format a number so that it's thousands are separated by commas. {{ number|format_thousands }}

  • format
  • string
  • comma
  • decimal
  • number
  • thousands
  • float
Read More