Login

All snippets written in Python

Snippet List

Fuzzy testing with assertNumQueries

Django 1.3 has an assertNumQueries method which will allows you to simply specify the number of queries you expect. Sometimes, however, specifying the exact number of queries is overkill, and makes the test too brittle. This code provides a way to make more forgiving tests. See http://lukeplant.me.uk/blog/posts/fuzzy-testing-with-assertnumqueries/

  • testing
  • performance
  • optimization
  • assertNumQueries
  • fuzzy
Read More

Run model validation before saving a model instance

How to validate your model at save using the pre_save signal. from http://groups.google.com/group/django-developers/browse_thread/thread/eb2f760e4c8d7911/482d8fd36fba4596?hl=en&lnk=gst&q=problem+with+Model.objects.create#482d8fd36fba4596

  • save
  • clean
  • pre_save
  • signals
  • validate
  • full-clean
  • full_clean
Read More

Campo para Validar CPF ou CNPJ Brasileiro

I basically mixed both BRCPFField and BRCNPJField to create a widget that validates either an CPF or an CNPJ. The doc strings are not localized. So you probably have to hardcode it yourself.

  • validation
  • field
  • widget
  • brazil
  • brasil
  • cnpj
  • cpf
Read More

Class based generic views that automatically check permissions

Simple wrappers around the new class-based generic views (introduced in Django 1.3) that also check permissions. **Example Usage** *(views.py)*: from mymodule import RestrictedListView, RestrictedUpdateView class MyListView(RestrictedListView): model = MyModel class MyUpdateView(RestrictedUpdateView): model = MyModel and so on for Create and Delete.

  • generic-views
  • permissions
  • class-based
Read More

Jcrop Form

Implements a Django form that integrates image uploading plus cropping using the awesome Jcrop plugin (http://deepliquid.com/content/Jcrop.html). NOTE: Still lacks proper error handling...

  • image
  • jquery
  • form
  • jcrop
Read More

Memento

This class tracks changes in Django Admin. When a save action is performed, it stores the value of the old object using the Memento model. Example of code for a model in **admin.py** for a custom 'app': from app.memento.models import Memento def save_model(self, request, obj, form, change): obj.save() data = serializers.serialize("json", [obj, ]) m = Memento(app="Unidade",model=modelName,data=data, user=request.user) m.save() class UnidadeAdmin(admin.ModelAdmin): pass UnidadeAdmin.save_model = save_model This stores the former values of 'Unidade' model on 'Memento' model data. Not tested on previous versions of Django, but could work on them too.

  • admin
  • register
  • changes
  • persistence
  • tracking
Read More

LinkShare Pixel Tracking template tag for Satchmo

Code for template tag which generate [**LinkShare**](http://www.linkshare.com/) Pixel Tracking code for [**Satchmo**](http://www.satchmoproject.com/)-based stores. Paste code into *linkshare_tracking.py* file in your project's template tags folder. Set *LINKSHARE_MERCHANT_ID* in your *settings.py* **Usage:** Put at top of *success.html* template: `{% load linkshare_tracking %}` Somewhere in *success.html* template body: `{% linkshare_pixeltracker request order %}`

  • satchmo
  • linkshare
  • pixel
  • pixeltracking
Read More

Decorator for authenticating token based API calls

Uses the token generator located at django.contrib.auth.tokens as an authentication mechanism aimed mainly at API calls. Any POST request with a valid token and user parameter will work as if the user were logged in normally.

  • decorator
  • login
  • auth
  • token
Read More

post_migrate handler to load initial SQL after migrating with south

I found that South doesn't execute initial sql file after a migration, like what Django can do after syncdb. So here's the workaround by using post_migrate signal. Usage: Put your SQL files the same way as you would if you were to use Django to load your initial SQL file (follow Django doc). The only difference is that, the SQL filename needs to in this format: <app_label>.sql OR <app_label>.<backend>.sql This is done this way since the migration is run per app.

  • custom-sql
  • south
  • initial-data
  • post_migrate
Read More

Automatic CRUD urls from your models...

Just extends your models from this One... is abstract so, it will not generate a table. Now, in your urls.py do this: from django.conf.urls.defaults import * from animals.models import Dog, Cat, Bird urlpatterns = patterns('animals.views', url(r'^$', 'index', {},Dog._meta.app_label), ) dog=Dog() cat=Cat() bird=Bird() urlpatterns+=dog.build_generic_CRUD_urls(Dog) urlpatterns+=cat.build_generic_CRUD_urls(Cat) urlpatterns+=bird.build_generic_CRUD_urls(Bird) then you can create the templates, and get the urls like this: {{ object.get_absolute_url }} View {{ object.get_update_url }} Edit {{ object.get_delete_url }} Delete {{ dummy_object.get_create_url }} Create dummy_object is a quick and dirty solution until I find some better... With all these you can create 54 functional and low detail CRUDS in one hour. :D Enjoy!

  • model
  • url
  • generation
Read More

Management command which helps to find temlate files

If you need to customize many default templates from installed apps, this management command will help you to find those templates and to copy them to desired location. Place this code at: management/commands/templates.py To see a list of installed templates, run: python manage.py templates To copy all templates to specified location: python manage.py templates --copy-to ./templates To copy templates from specified applications only: python manage.py templates admin auth --copy-to ./templates

  • management
  • commands
  • command
Read More

Fix for the bad behaviour of GenericForeignKey field

I don't know if you noticed but GenericForeignKey behaves badly in some situations. Particularly if you assign a not yet saved object (without pk) to this field then you save this object the fk_field does not get updated (even upon saving the model)- it's updated only upon assigning object to the field. So you have to save the related object prior to even **assigning** it to this field. It's get even more apparent when you have null=True on the fk/ct_fields, because then the null constrains won't stop you from saving an invalid object. By invalid I mean an object (based on a model with GFK field) which has ct_field set but fk_field=None. Maybe this problem is irrelevant in most use case scenarios but this behaviour certainly isn't logical and can introduce silent bugs to your code.

  • genericforeignkey
  • contenttypes
Read More

Drag and drop ordering of admin list elements for Grappelli

Adds drag-and-drop ordering of rows in the admin list view for [Grappelli](http://code.google.com/p/django-grappelli/). This is based on [Snippet #2057](http://djangosnippets.org/snippets/2057/) and fixes some bugs as well as switching to jQuery/jQuery UI provided by Grappelli. No additional files need to be installed. The model needs to have a field holding the position and that field has to be made list_editable in the ModelAdmin. The changes of the ordering are applied after clicking 'Save'.

  • admin
  • sort
  • jquery
  • order
  • sortable
  • grappelli
Read More

2955 snippets posted so far.