Login

All snippets

Snippet List

Plaintext password

Plaintext password hasher (encoded string: plain$1$mysecretpass). DANGEROUS!!! Use just if you know what you are doing!

  • password
  • hashes
  • plaintext
Read More

Email backend to BCC all emails

The backend lets you quickly get an idea of all emails that are sent out. Helpful for debugging or keeping an archive of all communications. Use instead of Django's SMTPBackend.

  • email
  • backend
  • bcc
Read More

Ultimate(?) export/download CSV admin action

This owes a debt to a number of earlier snippets by myself and others, including: *(most directly)* [#2868](http://djangosnippets.org/snippets/2868/), plus [#2020](http://djangosnippets.org/snippets/2020/), [#2712](http://djangosnippets.org/snippets/2712/), [#1697](http://djangosnippets.org/snippets/1697/) Use of OrderedDict means it requires Python 2.7+. You also need to `pip install singledispatch` which is a backport of a Python 3.4 feature. Singledispatch (along with custom attributes instead of a factory function) gives a very clean interface in your ModelAdmin, whether or not you need a custom `short_description`. This version allows you to (optionally) specify custom column labels, or to (optionally) use Django's usual prettifying mechanism (`field.verbose_name`). Thanks to #2868 it can do relation-spanning double-underscore lookups and also model attribute/method (rather than field) lookups for columns, just like you can in your ModelAdmin `list_display`.

  • csv
  • admin-actions
Read More

Test runner that installs 'tests' packages as apps

Ever tried to unit test custom fields or abstract models? If so, you probably used a solution like [this one](http://djangosnippets.org/snippets/2843/). It surely works, but it has some issues: 1. Runs 'syncdb' several times. 2. It's not automatic. You must add the mixin or copy the code to each of the TestCases. This test runner adds to INSTALLED_APPS the 'app.tests' package for **each of the specified** apps, **before the 'syncdb' happens**. This has the [discovery runner](https://pypi.python.org/pypi/django-discover-runner) as a dependency (for 1.5 only, it will be the default in 1.6). However, it comes as a mixin so it should be easily pluggable to other test runners. If you intend to use the mixin with other runners, note that it imports 'app.tests.models' so it won't work with tests modules (tests.py). Your runner must "use" test packages (like discovery runner). # USAGE # in your settings.py: TESTAPPS_INSTALL = ( 'app1', 'app2', # ... ) TEST_RUNNER = 'testapp_runner.DiscoverTestAppRunner' # example import path # extra apps in command line. # run test for apps 'app1' to 'app4', adding 'app3' and 'app4' to the TESTAPPS_INSTALL setting. manage.py test app1 app2 app3 app4 --with-test-app=app3 --with-test-app=app4

  • django
  • testing
  • apps
  • testrunner
  • test-runner
  • app-models
Read More

Get derived model instance

Get derived model without storing their names or content types in databases. You write only one line, it expands into only one SQL-query (with many LEFT OUTER JOIN's). Model definition example: class BaseModel(models.Model): foo = models.IntegerField(null=True) derived = DerivedManager() class FirstChild(BaseModel): bar = models.IntegerField(null=True) class SecondChild(BaseModel): baz = models.IntegerField(null=True) How to use: >>> f = FirstChild.objects.create() >>> s = SecondChild.objects.create() >>> print list(BaseModel.objects.all() [<BaseModel object 1>, <BaseModel object 2>] >>> print list(BaseModel.derived.all() [<FirstChild object 1>, <SecondChild object 2>] >>> print BaseModel.derived.get(pk=s.pk) <SecondChild object 2>

  • models
  • orm
  • inheritance
Read More

Accessing URL variable from within a Form

**Use case:** Suppose you are working on maintenance screens on some data objects. On one particular page (a form) you want to have exits directly back to a calling page (as a cancel operation) or indirectly back to the calling page (after an data update operation). However, the form and its object are not directly related to the target page (perhaps a one-to-many relationship) so you cannot figure the calling page from object data - but the target object IS referenced in the url. ** How To:** To make this work, we need to pick out a variable from the URL of the current page and use it to generate the URL of the target page. 1. [urls.py] Models *Banker* and *Iaccount* are related as One-to-Many so if we are creating an *Iaccount* we cannot usually determine the *Banker* object to return to. In this example, URL1 contains the variable `iid` - the primary key to the Banker object; this will render a create form. We want to be able to reference URL2 from this form. 2. [views.py: get_initial] We can access the variable we want with `self.kwargs['iid']` and use it to set the initial value of the `ident` fields which links back to the *Banker* object 3. [views.py: get_success_url] In the same way we can pass the value into the form's *success_url* to point at URL2 4. [template] In the template, we can also access the variable now as `form.ident.value` so we can construct a *Go Back* link to URL2 Thanks to Thomas Orozco for leading the way.

  • url
  • form
  • cbv
Read More

Model Mixin to Save Only Changed Fields

**[Improved and Released as Save The Change.](https://github.com/karanlyons/django-save-the-change)** Django 1.5 added the `update_fields` `kwarg` to `Model.save()`, which allows the developer to specify that only certain fields should actually be committed to the database. However, Django provides no way to automatically commit only changed fields if they're not specified. This mixin keeps track of which fields have changed from their value in the database, and automatically applies `update_fields` to update only those fields.

  • model
  • save
  • mixin
  • class
  • automatic
  • update_fields
Read More

Create a random integer in a template

Create a random integer with given length. - For a length of 3 it will be between 100 and 999. - For a length of 4 it will be between 1000 and 9999. Use it in a template like: {% random_number as my_id %} The id is {{ my_id }}

  • template
  • django
  • templatetag
  • integer
Read More

Logging to rotating files

It took me some time to figure out how to set up logging in Django. What I want to do is to log to a pair of rotating files each 1MB in size. What I come up with is this code segment in the `settings.py` file.

  • settings
  • logging
Read More

Many 2 Many Admin Ordering with Mysql

My Models has a FK to translations and also a many 2 many to categories which also them are translated With this code I concatenate the translation of the categories and allow the changelist to order them. works only on mysql but you can adapt to your DB SET SESSION is required by mysql.

  • admin
  • mysql
  • m2m
  • ordering
Read More

3109 snippets posted so far.