Login

Most bookmarked snippets

Snippet List

Load Template from App

Updated a similar snippet by "King" to work with Django 1.6. This is especially useful for overriding the admin templates without having to symlink or copy them into your project. For example {% extends "admin:base.html" %} would extend the admin page base.html.

  • template
  • admin
  • loader
  • app
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

Save Geolocation for an Address based model on save()

This code will work on any model using correct address data in its fields that also require latitude and longitude data to be updated on saving. It uses pythons own default urllib and json, so no need to install 3rd party stuff to make it work. This method is preferred to getting it on the fly, due to the OVER_QUERY_LIMIT that you will get when parsing many address, this way means it stays up to day in the model and will update when any part of the address changes.

  • Geolocation
  • Geolocation on save
  • Google Geolocation
Read More

Basic PDF view mixin and utils using reportlab.

Simplified version of the snippet that renders model to PDF [http://djangosnippets.org/snippets/2540/](http://djangosnippets.org/snippets/2540/) This PDF view mixin for Django Class Based Views. See working project example: https://github.com/elena/django-pdfmixin-example --- This is based on the case scenario where you have a model which has a `DetailView`. You then construct a bespoke PDF for the same model that is unrelated in any way to the `DetailView`. The PDF needs to be returned as a `HTTPResponse` object. The model object is provided.

  • pdf
  • mixin
  • reportlab
  • class-based-views
  • cbv
Read More

More generic CSV export admin action factory

based on #2020 This one is even more generic than the previous generic ones since you can specify in fields any attribute you will give to the admin interface and not just fields from the model. You can for example directly export the list_display as a list of fields, including look-ups for related attributes that you may have defined in a function inside the Admin Class

  • admin
  • csv
  • related
  • admin-actions
Read More

Lightweight querysets

Suppose you have two models A and B. The models have lots of large text/json fields and other heavy data. Your view is showing some list of `B.select_related(A)`, however, it is using just few lightweight fields. You want to defer all heavyweight fields in order to offload your DB and limit its traffic, but it is a tedious error prone work, that smells a bit with over-optimization. Real example, you have Product and Category objects. Both have large description fields with lots of text data. However, these fields are only needed on product detail page or on category detail page. In other cases (eg. side menu, some product suggestion block etc) you just need few lightweight things. Solution: add `LightweightMixin` to your models manager and specify your `heavyweight_fields` and `always_related_models`. # all visible products with necessary relations prefetched and heavyweight # fields deferred. qs = Product.objects.lightweight() # custom queryset with default defers applied. description and ingredients fields will # be normally deferred, but in this case they are explicitly selected qs = Product.objects.filter(my_filter="that", makes="sense") qs = Product.objects.as_lightweight(qs, select=('description', 'ingredients')) The best way to work with this snippet is to add the mixin to all managers in order to use `lightweight()` and `public()` calls. The `as_public()` is intended for your visibility, `select_related()` and `batch_select()` queryset settings. When you need full blown object, use `public()` queryset. When you need a lightweight list of objects, use `lightweight()` queryset. When your application is completed, check the database querylog for frequent unnecessary large and ugly queries. Group all queries that were made by `lightweight()` querysets, make a list of unnecessary heavy fields and add them to manager's `heavyweight_fields`. If your `as_public()` uses `select_related()` joining heavy objects, then you can also specify `always_related_models` to defer some fields of these relations too. Why? Because database IO will become your major bottleneck someday, just because you fetch 2Mb of data in order to render some tiny menu. With proper caching this is not a major issue, but proper queries may be sign of proper coding.

  • queryset
  • defer
  • lightweight
Read More

Convert multiple select for m2m to multiple checkboxes in django admin form

This is a javascript to call in the Media class of the ModelAdmin instance for the model, requires some additional css. The goal of such approach is that the add related functionality is supported, and works also with the django-mptt model fields. The new component can support resize functionality, in such case the jquery-ui resizable script is needed. For a complete documentation on this, and how to use it inside your project please visit this [blog post](http://www.abidibo.net/blog/2013/04/10/convert-select-multiple-widget-checkboxes-django-admin-form/)

  • django-admin
  • multiplecheckboxfield
  • multiple-select
  • django-mptt
Read More

convert youtube url for iframe, js api

[code] {% get_video_urls url as url_object %} or get object attribute: {% get_video_urls obj "url" as url_object %} {{ url_object }} original url {{ url_object.video_id }} original url or video_id {{ url_object.resource }} youtube, vimeo, None {{ url_object.iframe_url }} original url or iframe_url {{ url_object.js_api_url }} original url or js_api_url [/code]

  • url
  • youtube
  • embed
  • iframe
  • vimeo
  • video_id
Read More

Django-Celery Progress Bar backend

This is my POC code for a progress bar backend (for delivering JSON to some AJAX frontend) in Django using Django-Celery (with RabbitMQ). It is quite concise, yet it took me a while to get there because Celery's Documentation is IMHO rather puristic. Web development is meant to be copy-paste! Here you go!

  • progress
  • celery
Read More

Class-based view mixin for flatpages

Allows you to include content from flatpages in class-based views. You can specify the url for the flatpage you want, or let it be determined by request.path.

  • mixin
  • flatpages
  • class-based-views
Read More

Custom collectstatic that uses etag and md5 digests to determine whether files on S3 have changed

For use with S3 BotoStorage STATICFILES_STORAGE ="storages.backends.s3boto.S3BotoStorage" and AWS_PRELOAD_METADATA = True Custom management command that compares the MD5 sum and etag from S3 and if the two are the same skips file copy. This makes running collect static MUCH faster if you are using git as a source control system which updates timestamps.

  • s3
  • amazon
  • aws
  • boto
  • collectstatic
  • storages
Read More

Pagination helper

You have pagination for some blog. At the bottom of the page you have space for seven page links. This module tries to always fill out those slots. It handles the corner cases for first page and last page etc. The logic for this is complex and sadly the Django pagination module does not deal with this. Also, it's a hell to implement this in Django templates. Believe me. See pydoc for detailed documentation. Running tests was done with `doctest`.

  • pagination
Read More

3110 snippets posted so far.