Login

All snippets

Snippet List

Improved Pickled Object Field

[Based on snippet #513 by obeattie.](http://www.djangosnippets.org/snippets/513/) **Update 10/10/09:** [Further development is now occurring on GitHub, thanks to Shrubbery Software.](http://github.com/shrubberysoft/django-picklefield) Incredibly useful for storing just about anything in the database (provided it is Pickle-able, of course) when there isn't a 'proper' field for the job. `PickledObjectField` is database-agnostic, and should work with any database backend you can throw at it. You can pass in any Python object and it will automagically be converted behind the scenes. You never have to manually pickle or unpickle anything. Also works fine when querying; supports `exact`, `in`, and `isnull` lookups. It should be noted, however, that calling `QuerySet.values()` will only return the encoded data, not the original Python object. *Please note that this is supposed to be two files, one fields.py and one tests.py (if you don't care about the unit tests, just use fields.py).* This PickledObjectField has a few improvements over the one in [snippet #513](http://www.djangosnippets.org/snippets/513/). 1. This one solves the `DjangoUnicodeDecodeError` problem when saving an object containing non-ASCII data by base64 encoding the pickled output stream. This ensures that all stored data is ASCII, eliminating the problem. 2. `PickledObjectField` will now optionally use `zlib` to compress (and uncompress) pickled objects on the fly. This can be set per-field using the keyword argument "compress=True". For most items this is probably **not** worth the small performance penalty, but for Models with larger objects, it can be a real space saver. 3. You can also now specify the pickle protocol per-field, using the protocol keyword argument. The default of `2` should always work, unless you are trying to access the data from outside of the Django ORM. 4. Worked around a rare issue when using the `cPickle` and performing lookups of complex data types. In short, `cPickle` would sometimes output different streams for the same object depending on how it was referenced. This of course could cause lookups for complex objects to fail, even when a matching object exists. See the docstrings and tests for more information. 5. You can now use the `isnull` lookup and have it function as expected. A consequence of this is that by default, `PickledObjectField` has `null=True` set (you can of course pass `null=False` if you want to change that). If `null=False` is set (the default for fields), then you wouldn't be able to store a Python `None` value, since `None` values aren't pickled or encoded (this in turn is what makes the `isnull` lookup possible). 6. You can now pass in an object as the default argument for the field without it being converted to a unicode string first. If you pass in a callable though, the field will still call it. It will *not* try to pickle and encode it. 7. You can manually import `dbsafe_encode` and `dbsafe_decode` from fields.py if you want to encode and decode objects yourself. This is mostly useful for decoding values returned from calling `QuerySet.values()`, which are still encoded strings. The tests have been updated to match the added features, but if you find any bugs, please post them in the comments. My goal is to make this an error-proof implementation. **Note:** If you are trying to store other django models in the `PickledObjectField`, please see the comments for a discussion on the problems associated with doing that. The easy solution is to put django models into a list or tuple before assigning them to the `PickledObjectField`. **Update 9/2/09:** Fixed the `value_to_string` method so that serialization should now work as expected. Also added `deepcopy` back into `dbsafe_encode`, fixing #4 above, since `deepcopy` had somehow managed to remove itself. This means that lookups should once again work as expected in **all** situations. Also made the field `editable=False` by default (which I swear I already did once before!) since it is never a good idea to have a `PickledObjectField` be user editable.

  • model
  • db
  • orm
  • database
  • pickle
  • object
  • field
  • type
  • pickled
  • store
Read More

cache_page that does nothing

When debugging/developing you want to be able to refresh your views every time you make a little change. But when in production mode you might want to cache these views because they contain long and resource hungry calculations or something. By putting this above "hack" in after importing `cache_page` you only cache the views in production mode.

  • cache
  • decorator
  • cache_page
Read More

Limit ManyToMany fields in forms

Limit ManyToMany fields in forms. Hide the field, if only one item can be selected. e.g. For limit sites choices only to accessible sites. Also available via django-tools: http://code.google.com/p/django-tools/

  • forms
  • manytomany
Read More

Facebook event selector field

Ripped this out of a project I'm working on. The field renders as two <select> elements representing the two-level hierarchy organized events Facebook uses. Returns the id's Facebook wants.

  • forms
  • field
  • widget
  • facebook
  • fbml
  • fbjs
Read More

Updated - Template context debugger with (I)Pdb

Tag to inspect template context, filter to inspect variable. Originally by denis, [http://www.djangosnippets.org/snippets/1550/](http://www.djangosnippets.org/snippets/1550/). This just extracts variables from the context to locals for quicker access and autocompletion (When using ipdb). Additionally, 'vars' holds context keys for quick reference to whats available in the template.

  • template
  • debug
  • context
  • pdb
  • ipdb
Read More

Month / Year dropdown widget

This is an adaption of [django.forms.extras.widgets.SelectDateWidget](http://code.djangoproject.com/browser/django/trunk/django/forms/extras/widgets.py#L16) which has no day dropdown - it still produces a date but with the day set to 1. Example use class myForm(forms.Form): # ... date = forms.DateField( required=False, widget=MonthYearWidget(years=xrange(2004,2010)) )

  • date
  • year
  • credit-card
  • month
Read More

Private Context Decorator

Django's standard inclusion_tag doesn't include context variables by default. When you add takes_context you are required to manually merge the context variables into the dict which your tag returns, which tends to result in wasteful code or [possibly accidentally] leaking variables into the global context (`context.update({…})`). This decorator allows your inclusion tag to remain simple and still have safe access to the global context for things like `MEDIA_URL`: @register.inclusion_tag('my_template') @private_context def my_tag(context, …): return {"foo": 1, "bar": 2}

  • templatetag
  • decorator
  • context
  • inclusion_tag
Read More

match filter

A filter that re.matches a regex against a value. Useful for nav bars as follows: {% if location.path|match:"/$" %} class="current"{% endif %} For `location.path` see my [location context_processor](/snippets/1685/).

  • regex
  • match
  • nav
Read More

location context_processor

A simple context_processor to include location info. Useful for permalinks, site name references, and navigation bars. For example: {% if location.path|match:"/$" %} class="current"{% endif %} See also my [match filter](/snippets/1686/).

  • url
  • path
  • location
  • nav
Read More

Django Template "include_raw" tag

At WWU Housing, we started using the [Tempest jQuery plugin](http://plugins.jquery.com/project/tempest) for javascript templating, which has the same {{ var }} syntax as Django's templating. We wanted to be able to use the same templates in our server-side python and our client-side js, so we had to have a way of including the unrendered template for the js. At the same time, for convenience, it had to be modular so we could push the same code from our dev- to our live-server and not worry about absolute paths (which is why the {% ssi %} tag did not work). So the {% include_raw %} tag was born.

  • template
  • django
  • parse
  • include
  • ssi
Read More

is_dirty and dict of changed values

When you call model.changed_columns() you get a dict of all changed values. When you call model.is_dirty() you get boolean whether or not the object has been changed since last save Based on an answer here:http://stackoverflow.com/questions/110803/dirty-fields-in-django but fixed and added is_dirty

  • django
  • models
  • save
  • dirty
Read More

CSV to JSON Fixture

**This script converts a CSV file into a JSON file ready to be imported via `manage.py loaddata` like any other fixture data.** It can be used manually to do a one-time conversion (for placing into a /fixtures folder), or used in a fabric script that automatically converts CSV to JSON live then runs `loaddata` to import as fixture data. To run script: >`csv2json.py input_file_name model_name` > >e.g. csv2json.py airport.csv app_airport.Airport > >Note: input_file_name should be a path relative to where this script is. **Scripts depends on simplejson module.** The module can just be placed in a sub-folder to the script to make it easy to import. If you use the same Python binary that you use for your Django site, you could use the Django import instead: `from django.utils import simplejson` **File Input/Ouptut formats:** Assumes CSV files are saved with LF line endings, and that first line has field values. First column is the model's pk field. Sample CSV input: id,ident,name,city,state 1,00C,Animas Air Park,Durango,CO 6,00V,Meadow Lake,Colorado Springs,CO 7,00W,Lower Granite State,Colfax,WA 12,01J,Hilliard Airpark,Hilliard,FL Output file name is input name + ".json" extension. Sample JSON output: [ { "pk": 1, "model": "app_airport.Airport", "fields": { "name": "Animas Air Park", "city": "Durango", "ident": "00C", "state": "CO", } } ] **Debugging Conversion Problems** If JSON import errors out with "ValidationError: This value must be an integer", you probably have a blank in an Integer field within your CSV file, but if can't figure out, try setting a breakpoint in file: ./django/django/db/models/fields/__init__.py e.g. 688 try: 689 return int(value) 690 except (TypeError, ValueError): 691 import pdb; pdb.set_trace() 692 -> raise exceptions.ValidationError( 693 _("This value must be an integer.")) To figure out what field caused the error, while in the debugger: (Pdb) u <- to go UP the callstack (Pdb) field.name

  • json
  • loaddata
  • fixtures
  • csv
  • import
  • fixture
Read More

superSearch function for generating large OR queries

superSearch is intended to make it easier to make complex OR queries, thusly hitting the database less. EXAMPLE: Searching for a user named 'Eric Neuman' would be difficult because first_name and last_name are separate fields. However, with superSearch, it's a breeze. query = ['Eric Neuman'] f = ['first_name','last_name'] s = query.split(' ') m = ['icontains'] results = superSearch(User, f, m,s)

  • dynamic
  • q
  • query
  • kwargs
Read More

3110 snippets posted so far.