Login

Top-rated snippets

Snippet List

group_required decorator

This snippet provides a @group_required decorator. You can pass in multiple groups, for example: @group_required('admins','editors') def myview(request, id): ... Note: the decorator is based on the snippet [here](http://fragmentsofcode.wordpress.com/2008/12/08/django-group_required-decorator/) but extends it checking first that the user is logged in before testing for group membership - [user_passes_test](http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.decorators.user_passes_test) does not check for this by default. It is important to check that the user is first logged in, as anonymous users trigger an AttributeError when the groups filter is executed.

  • decorator
  • auth
  • groups
Read More

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

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

SQL Log To Console Middleware

When running the Django development server, this middleware causes all executed SQL queries to get printed out to the console. This is based on [Snippet 161](http://www.djangosnippets.org/snippets/161/). The big difference is that 161 logs by adding stuff to your response text, which isn't very convenient IMO.

  • sql
  • middleware
  • log
  • debug
  • logging
  • console
Read More

automatic urlpattern creator

This method creates urlpatterns based on view functions that have 'request' as their first parameter. See docstring for details.

  • url
  • urlconf
  • patterns
  • auto
  • urlpattern
Read More

Append paramaters to a GET querystring (template tag)

This tag is designed to facilitate pagination in the case where both the page number and other parameters (eg. search criteria) are passed via GET. It takes one argument - a dictionary of GET variables to be added to the current url Example usage: {% for page_num in results.paginator.page_range %} <a href="{% append_to_get p=page_num %}">{{ page_num }}</a> {% endfor %} Note that the passed arguments are evaluated within the template context.

  • get
  • pagination
  • request
Read More

Extended logging module

The django_admin_log only logs changes, not simple requests. Sometimes it can be useful to log when a user of your admin interface is checking out important data, for instance if you are making a system with personal sensitive data, that needs to comply with government / company policies. This will log such hits to the django_admin_log by overriding the change_view method in ModelAdmin. So you must override this method in all classes you want to have logged.

  • log
  • request
  • logging
  • django-admin
  • django_admin_log
  • extended
  • change_view
Read More

Custom CSS class in Form with template tag filter

A lot of times we need to insert a specific **CSS class** into a Form instance for it to be rendered in the template. The current method is to specify the CSS class in the Python code through the form field widget. But it would be easier for the designer to be able to specify the CSS class in the template directly. For example rather than doing this in your Python code: 'name = forms.CharField(widget=forms.TextInput(attrs={'class':'special'}))` You can do this in your template: `{{ form.name|cssclass:"special"}}` This template filter only works with Form Field instance.

  • css
  • form
  • class
Read More

User groups template tag

This tag builds on top of the [ifusergroup/else tag](http://www.djangosnippets.org/snippets/390/), fixes a small bug and introduces support for else blocks. This adds a way to provide multiple groups via group1|group2|group3

  • tag
  • templatetag
  • user
  • auth
  • group
Read More

Sorl Thumbnail + Amazon S3

**General notes:** - Set MEDIA_URL (or whatever you use for uploaded content to point to S3 (ie. MEDIA_URL = "http://s3.amazonaws.com/MyBucket/")) - Put django-storage in project_root/libraries, or change the paths to make you happy. - This uses the functionality of django-storage, but *not* as DEFAULT_FILE_STORAGE. The functionality works like so: **Getting stuff to S3** - On file upload of a noted model, a copy of the uploaded file is saved to S3. - On any thumbnail generation, a copy is also saved to S3. **On a page load:** 1. We check to see if the thumbnail exists locally. If so, we assume it's been sent to S3 and move on. 2. If it's missing, we check to see if S3 has a copy. If so, we download it and move on. 3. If the thumb is missing, we check to see if the source image exists. If so, we make a new thumb (which uploads itself to S3), and move on. 4. If the source is also missing, we see if it's on S3, and if so, get it, thumb it, and push the thumb back up, and move on. 5. If all of that fails, somebody deleted the image, or things have gone fubar'd. **Advantages:** - Thumbs are checked locally, so everything after the initial creation is very fast. - You can clear out local files to save disk space on the server (one assumes you needed S3 for a reason), and trust that only the thumbs should ever be downloaded. - If you want to be really clever, you can delete the original source files, and zero-byte the thumbs. This means very little space cost, and everything still works. - If you're not actually low on disk space, Sorl Thumbnail keeps working just like it did, except your content is served by S3. **Problems:** - My python-fu is not as strong as those who wrote Sorl Thumbnail. I did tweak their code. Something may be wonky. YMMV. - The relative_source property is a hack, and if the first 7 characters of the filename are repeated somewhere, step 4 above will fail. - Upload is slow, and the first thumbnailing is slow, because we wait for the transfers to S3 to complete. This isn't django-storage, so things do genuinely take longer.

  • image
  • thumbnail
  • s3
  • amazon
  • sorl
Read More

SortableModel - abstract model class for sortable records

If you have a model that has an "ordering" column, and you want to be able to re-position records (eg, order items by priority), this base class should make it fairly easy. To use it, you extend your model using this abstract class, then hook up the pre_save event to the pre_save event of the base class, and you're good to go. Whenever you save an item, it ensures that it has a valid "order" number. The meat of this class is the "move()" method. Just call instance.move(number) where instance is your model instance, and this class will do all the logic necessary to shift around the order numbers for you.

  • sort
  • order
  • sortable
  • orderable
  • sorted
  • ordered
Read More

Filtering foreignkey fields in django admin

Sometimes you need to filter foreignkey choices in admin interface, to objects created by user or meeting some other condition. In django 1.0 there is no formfield_for_foreignkey method in ModelAdmin class so we have to make a workaround. Here is the solution I have found to be the easiest for me.

  • filter
  • admin
  • foreignkey
Read More

Updated table tag

This table tag helps with render tables, which can be fairly complex. I updated the previous table tag (296). I added support for oddrow,evenrow,lastcellinrow,oddcol,evencol. And made a few minor adjustments to syntax formatting, and some non needed if conditionals These are all of the supported variables available in the context {{table.counter0}} {{table.counter}} {{table.rowcounter0}} {{table.rowcounter}} {{table.startrow}} {{table.endrow}} {{table.oddrow}} {{table.evenrow}} {{table.firstrow}} {{table.lastrow}} {{table.firstcell}} {{table.lastcell}} {{table.lastcellinrow}} {{table.evencol}} {{table.oddcol}} {{table.parenttable}}

  • template
  • tag
  • python
  • table
Read More

3110 snippets posted so far.