Login

Top-rated snippets

Snippet List

Unlimited-length CharField

Unlimited-length character fields in Postgres perform the same as limited-length fields, and the Postgres manual suggests not arbitrarily limiting these fields. Unfortunately, Django does not provide a way to access unlimited-length character fields except using TextField, which is rendered differently in forms and in the admin, and has different connotations. LongCharField is a way to avoid putting arbitrary max_length values where they aren't required. It will only work with databases that allow VARCHAR with no numeric parameters, such as Postgres. MySQL won't work.

  • text
  • field
  • postgres
  • charfield
  • length
  • max_length
  • unlimited
  • varchar
Read More

Feet and Inches FormField/Widget

Feet and Inches Widget/Field allows users to enter a value in feet, inches and fractional inches and have that value stored as a decimal in your database of choice. I have this code broken out into separate files, but you can always combine to suit your needs. I have designated file delineation with a single line comment and the name of the file as referenced in the import statements. The INCH_DECIMALS and INCH_FRACTION constants may be modified to allow smaller increments. My needs for this implementation only required accuracy to 1/16. Hope this helps someone learn how to use the MultiWidget and MultiValueFields! Happy Coding.

  • widget
  • multiwidget
  • multifield
  • feet
  • inches
Read More

View response's content in a browser while testing

I often insert `pdb.set_trace()` in my test cases to debug and examine behavior. When tests fail with assertions like `assertContains(response, 'Some text')`, it would be useful to see the response's contents in a browser window. This snippet does just that. Simply put this code in a python script on your `PYTHONPATH` and import/call the function when the debugger starts. Only tested on Ubuntu and you might want to change `URL_OPENER` to whatever you want to open the URLs. Simple, but hopefully useful.

  • debug
  • test
  • response
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

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

orm_tools

This module contains classes that add new behavior to Django's ORM. Classes include: **Session** * Forces QuerySet objects to return identical instances when objects with the same primary key are queried. * Similar to [SQLAlchemy Session](http://www.sqlalchemy.org/docs/orm/session.html) **GraphSaver** * Save entire object graphs at once. * Automatically detects object dependencies and saves them in the correct order. **Collection** * Easier one-to-many relationships. Instructions and more information on [limscoder.com](http://www.limscoder.com/2011/01/django-orm-tools.html).

  • session
  • db
  • orm
Read More

cleat_list

Clear list from unwanted elements, within django template.

  • template
  • filter
  • list
  • clear
Read More

View to retrieve objects meeting a complex tag query

This view parses complex tag queries. It generates a list of model instances matching an expression of tags. The expression currently supports intersection, union and subtraction. Expressions can also be put in parenthesis and then combined with other expressions. The expression must be passed to this view in the tag_expression argument. In my application this is simply passed from the URL querystring. This snippet uses the django-tagging app. It assumes that tags are composed of alphanumeric characters, underscores, hyphens and spaces, but the django-tagging application allows tags with other characters, so you might either want to restrict users to using tags that only contain the above characters, or you might prefer to improve this snippet. Example: This URL http://example.com/people/?(deceased&parrot)|"Monty Python" will retrieve all people who are either deceased parrots or members of Monty Python. In the tag_expression argument: * ALL is treated as a keyword. If you happen (by some sad chance) to have a tag called ALL and want to use it in the expression, surround it in quotation marks. E.g. "ALL" * Examples: - famous -returns all instances of the model tagged with famous - famous&deceased -returns all instances of the model tagged both famous and deceased. - famous|deceased -returns all instances of the model tagged famous or deceased. - parrot-deceased -returns all alive parrots in the model. - ALL-deceased -returns all instances of the model that are not tagged deceased. - ALL -returns all instances of the model - "ALL" -returns all instances of the model that are tagged ALL - "great author"&deceased -returns all models tagged as great authors and deceased. Arguments: * request -- HTTP Request object * tag_expression -- a set expression of tags, supporting intersection, union, parenthesis and difference * app_name -- App for the model we're working on (defaults to pubman) * model_name -- Model on which to apply the set operations (defaults to Article) * view -- view to redirect to after the model instance list has been constructed * html_template -- HTML template to redirect (defaults to 'pubman/tag.html')

  • view
  • django-tagging
  • tag expression
Read More

3110 snippets posted so far.