Login

Most bookmarked 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

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

Management command to list custom management commands

I work with multiple projects, many of which have multiple custom management commands defined. It can be hard to remember them, and slow to pick them out of the "manage.py help" list. This quickie command lists all of a project's custom commands (along with their help text). Writing it was easy after looking at the source of django.core.management. Open questions include: how do you decide which app to put this command in? Should this command list itself?

  • management
  • commands
Read More
Author: pbx
  • 5
  • 8

manage.py for eclipse with pydev debugging

This code is referenced in a [screencast](http://blog.vlku.com/index.php/2009/06/10/djangoeclipse-with-code-complete-screencast/) focused on showing a user how to configure Eclipse with PyDev to give you code complete, and breakpoints inside the IDE. It comes from a [2007 blog post](http://bear330.wordpress.com/2007/10/30/how-to-debug-django- web-application-with-autoreload/) (I've replicated it in case that post ever disappears.)

  • debugging
  • pydev
  • eclipse
Read More

TextField

Alex Gaynor presented this idiom at EuroDjangoCon 2009.

  • forms
  • textfield
Read More

Python Calendar wrapper template tag

This tag gives you an iterable Python [Calendar object](http://docs.python.org/library/calendar.html) in your template namespace. It is used in the [django-calendar](http://github.com/dokterbob/django-agenda) project. Use it as follows in your template: {% get_calendar for <month_number_or_variable> <year_or_variable> as calendar %} <table> <tr> <th>Mon</th> <th>Tue</th> <th>Wed</th> <th>Thu</th> <th>Fri</th> <th>Sat</th> <th>Sun</th> </tr> {% for week in calendar %} <tr> {% for day in week %} <td>{{ day.day }}</td> {% endfor %} </tr> {% endfor %} </table>

  • template
  • tag
  • date
  • calendar
Read More

Authenticate against Active Directory - LDAP (my version)

This is based on [snippet 501](http://www.djangosnippets.org/snippets/501/), with some corrections: 1. if user doesn't exist and AD.authenticate passes, then create new user - don't store password - prevent default django auth backend authentication 2. if user exists and AD.authenticate passes - django User object is updated 3. various error handling 4. fixes (some mentioned in original snippet) 5. some settings removed from settings to backend module 6. other changes (ADUser class, re-indent, logging etc.) 7. ignores problem with search_ext_s (DSID-0C090627) 8. caching connection - when invalid then re-connect and try again Note that there is also ldaps:// (SSL version) django auth backend on [snippet 901](http://www.djangosnippets.org/snippets/901/). Possible improvements: 1. define new settings param - use secured - then LDAPS (snippet 901) 2. define new settings extra ldap options - e.g. protocol version 3. fetch more data from AD - fill in user data - maybe to make this configurable to be able to update user.get_profile() data too (some settings that has mapping AD-data -> User/UserProfile data)

  • auth
  • ldap
  • active-directory
  • backend
Read More

Hide Emails

Example Usage in the template: <p>{{ email|hide_email }}<br /> {{ email|hide_email:"Contact Me" }}<br /> {% hide_email "[email protected]" %}<br /> {% hide_email "[email protected]" "John Smith" %}</p> {{ text_block|hide_all_emails|safe }} All hidden emails are rendered as a hyperlink that is protected by javascript and an email and name that are encoded randomly using a hex digit or a decimal digit for each character. Example of how a protected email is rendered: <noscript>(Javascript must be enabled to see this e-mail address)</noscript> <script type="text/javascript">// <![CDATA[ document.write('<a href="mai'+'lto:&#106;&#x6f;&#x68;&#x6e;&#x40;&#101;&#120;&#97;&#109;&#x70;&#108;&#x65;&#46;&#x63;&#111;&#109;">&#74;&#111;&#104;&#110;&#x20;&#83;&#x6d;&#x69;&#x74;&#104;</a>') // ]]></script>

  • email
  • hide
  • protect
Read More

Django Akismet

http://sciyoshi.com/blog/2008/aug/27/using-akismet-djangos-new-comments-framework/

  • akismet
Read More

Use MEDIA_URL in 500 error page

The default server_error view uses Context instead of RequestContext. If you were depending on a context processor to make MEDIA_URL available in your templates, your 500.html template will not render with the correct image paths. This handler adds MEDIA_URL (and nothing else) back to the context that is sent to the template.

  • media
  • 500
  • handler
  • servererror
Read More

Simple E-mail registration

This is a simplified rip-off of django-registration and the built-in forms and views in contrib.auth. It requires no models and is very customizable. Saving the form creates a user with an unusable password and sends a password reset email (by default, uses the password reset template too). You must create templates/registration_form.html and the view registration_complete. I ripped this out of my site, which has a more complicated form, so I may be missing a few other things here.

  • registration
  • email
Read More

Choices class

Yet another class to simplify field choices creation. Keeps order, allows i18n. Before: ONLINE = 0 OFFLINE = 1 STATES = ( (ONLINE, _('online')), (OFFLINE, _('offline')) ) state = models.IntegerField(choices=STATES, default=OFFLINE) After: STATES = Choices( ('ONLINE', _('online')), ('OFFLINE', _('offline')) ) state = models.IntegerField(choices=STATES, default=STATES.OFFLINE)

  • models
  • choices
Read More
Author: dc
  • 7
  • 8

update_or_create

Django provides a `get_or_create` helper method in the `models.Manager` class which looks up an object for the given `kwargs`, creating one if necessary. But sometime you need a method which updates the object with given `kwargs` or creates it if it's not found. This snippet provides the helper for that purpose. Use the snippet like this: from django.db import models class PersonManager(models.Manager): update_or_create = _update_or_create class Person(models.Model): first_name = models.CharField() last_name = models.CharField() city = models.CharField() objects = PersonManager() person, created, updated = Person.objects.update_or_create(first_name="John", last_name="Smith", defaults=dict(city="London")) The method returns a tuple of (`object`, `created`, `updated`), where `created` and `updated` are booleans specifying whether an `object` was created or updated respectively. Both `created` and `updated` are `false` if `object` is neither created nor updated (that is `object` has just been fetched "as is" from db). This happens if the update fails.

  • model
  • helper
  • update
  • create
Read More

3110 snippets posted so far.