Login

Most bookmarked snippets

Snippet List

Simple Paginate

This function wraps boilerplate code to get the current page in a view, obtaining the page number from some URL query string variable, e.g., ?page=2 The interface is inspired by the interface of Paginator. The implementation follows an example given in Django documentation.

  • pagination
  • paginator
  • paginate
Read More

Proper fixtures loading in south data migrations

South documentation [contains a description](http://south.readthedocs.org/en/0.7.6/fixtures.html#fixtures-from-migrations) of the way you can load fixtures inside the data-migrations. def forwards(self, orm): from django.core.management import call_command call_command("loaddata", "my_fixture.json") It seems pretty clear and easy, but in fact it does not work the way you expect from south migrations, because the fixture loading does not engage the **orm** object. So, it allows **loaddata** management command to use standard models loading mechanism, and it would provide the most recent version of the models, obviously, which may not correspond to the schema of the fixture`s data. To be ensured that migration will use appropriate version of the models for fixture loading you could use code like follows: class Migration(DataMigration): def forwards(self, orm): load_fixture('my_fixture.json', orm) class Migration(DataMigration): def forwards(self, orm): with southern_models(orm): call_command("loaddata", "my_fixture.json")

  • fixtures
  • migration
  • fixture
  • south
  • datamigration
Read More

CompressedTextField for Django 1.4+

This snippet *updates* http://www.djangosnippets.org/snippets/383/ and http://www.djangosnippets.org/snippets/1495/ for Django 1.4+, and adds support for sqlite3 and south. Original snippet text: A CompressedTextField to transparently save data gzipped in the database and uncompress at retrieval.

  • text
  • model
  • field
  • compressed
  • gzip
  • south
Read More

Custom change_list filter based on SimpleListFilter shows only referenced (related, used) values

Since Django 1.4 you can create your own filters for change list view. If you want to show just used/related items in filter chooser you can use this snippet. Original idea from [here](http://jmduke.net/post/39953950546/custom-admin-filters-in-django). Big thanks to author. Improved class names for better clarity and use of model_admin.model instead of hardcoded model name. In example you can see two models - City and Country. City has ForeignKey to Country. If you use regular list_filter = ('country',) you will have all the countries in the chooser. This snippet however filters only related countries - the ones that have at least one relation to city.

  • ForeignKey
  • Filter
  • SimpleListFilter
Read More

JSON decorator for views handling ajax requests

Sample usage for using decorator `@json_response(ajax_required=True, login_required=True)` `def subscribe(request):` ` return {"status":"success"}` Converts a function returning dict into json response. Does is_ajax check and user authenticated check if set in flags. When function returns HttpResponse does nothing.

  • ajax
  • json
  • decorator
  • jsonp
Read More

CommaSeparatedIntegerField with CheckboxSelectMultiple Widget

This snippet allows you to use the CommaSeparatedIntegerField to store a set of integers that correspond to a set of choices. There are a couple other snippets that proclaim to do this, but they either don't work with the django 1.4, or are more complex.

  • MultipleChoiceField
  • CheckboxSelectMultiple
  • CommaSeparatedIntegerField
Read More

Django admin inline ordering - javascript only implementation

Having spent ages trying out various admin inline ordering packages and examples I found on here and elsewhere I failed to find a single one that did what I was after in the way I wanted or that worked, so I wrote one! The general idea for this version was to be done purely in javascript, no additional methods or parameters required on your models, it's designed to be stuck in a js file and included in your admin class Media js parameter: class Media: js = ['js/admin/widget_ordering.js', ] Your model should have an integer column for sorting on, the name of this column should go in the 'sort_column' parameter at line 3 and your model should also obviously specify this in it's Meta 'ordering' class: class Meta: ordering = ('rank',) That's it! This is a pretty basic implementation that adds simple up and down buttons next to the sort order field, if you want to adapt this to use drag and drop or something, please feel free!

  • admin
  • sorting
  • ordering
  • inline
  • tabular-inlines
Read More

Django Admin Speedup for big tables on postgres

The code is Django 1.4 version of code based on the [Django 1.3 snippet](http://djangosnippets.org/snippets/2593/) that speeds up Django's admin pages with postgres back-end for big tables (> few hundred thousands of records).

  • postgres
  • speed
  • optimization
  • django-admin
Read More

Login Required Middleware with Next Parameter

Based on [onecreativenerd](http://djangosnippets.org/users/onecreativenerd/) code. Sometimes it's a real pain to use the @login_required decorator all over the views of a complicated site. This middleware requires login on every page by default and supports a list of regular expression to figure out the exceptions. This way you don't have to worry about forgetting to decorate a view. This snippet requires LOGIN_URL to be set in settings.py, and optionally allows you fill out LOGIN_EXEMPT_URLS, a tuple of regular expressions (similar to urls.py) that lists your exceptions. Example: LOGIN_EXEMPT_URLS = ( r'^about\.html$', r'^legal/', # allow the entire /legal/* subsection )

  • middleware
  • django
  • login
  • login_required
  • next
Read More

Tastypie MongoDB Resource

MongoDB Resource for Tastypie ============================= Allows you to create delicious APIs for MongoDB. Settings -------- MONGODB_HOST = None MONGODB_PORT = None MONGODB_DATABASE = "database_name" Example of Usage ---------------- from tastypie import fields from tastypie.authorization import Authorization from tastypie_mongodb.resources import MongoDBResource, Document class DocumentResource(MongoDBResource): id = fields.CharField(attribute="_id") title = fields.CharField(attribute="title", null=True) entities = fields.ListField(attribute="entities", null=True) class Meta: resource_name = "documents" list_allowed_methods = ["delete", "get", "post"] authorization = Authorization() object_class = Document collection = "documents" # collection name Github Repository ================= <https://github.com/fatiherikli/tastypie-mongodb-resource>

  • tastypie
  • mongodb
Read More

List all errors in a form +bootstrap highlighting

Use this snippet to list all errors in a form. The message will be shown in a boostrap-type alert which can be 'closed' using a dismiss button. The **field label** and the **error** will be listed. e.g. > * Name: This field is required > * Email: Please enter a valid email

  • template
  • forms
  • error
  • form
  • list
  • errors
Read More

Filter by taggit tags in the admin (Django 1.4)

A *SimpleListFilter* derived class that can be used to filter by taggit tags in the admin. To use, simply add this class to the *list_filter* attribute of your ModelAdmin class. Ex.: class ItemAdmin(admin.ModelAdmin): list_display = ('name', 'unit', 'amount') list_filter = ('unit', TaggitListFilter) Based in [ModelAdmin.list_filter documentation](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter).

  • filter
  • tag
  • admin
  • tags
  • tagging
  • taggit
Read More

Database backup with admin command

Detect type of database (MySQL, PostgreSQL or SQLite) and make backup. In this moment ONLY WORK in GNU/Linux, NOT WIN.

  • database
  • admin-actions
  • backup
  • MySQL
  • admin-command
  • SQLite
  • PostgreSQL
Read More
Author: jhg
  • 1
  • 3

Convert Q object to function

This is a function to take a Q object and construct a function which returns a boolean. This lets you use the exact same filter syntax that Django's managers use and apply it inside list comprehensions, or to non-persistent objects, or to objects of different types with the same attribute names.

  • q-objects
  • field
  • queryset
Read More

3110 snippets posted so far.