Login

All snippets written in Python

Snippet List

Check Size of Object in memcached

I've been working with a data set where a single object won't fit into memcached's 1 Mb slab limit. The two functions have been useful to me for debugging the size of the data structure once pickled, and if said pickled data structure is greater than 1 Mb. These functions assume CACHE_BACKEND is memcached, obviously.

  • memcache
  • cache
  • memcached
Read More

Filter for adding quote marks

A template filter for adding curly quotes around a string. The filter understands enough HTML to put the quotes inside an initial paragraph begin and ending paragraph end, if they exist. Put the code inside a file in a templatetags subdir in your app, add a {% load myfile %} statement and you're ready to go with {{somebodysays|addquotes}}. Of course, beware the script kiddies, be careful with escaping.

  • templatetag
  • quotes
Read More

Obfuscator for django project sources

This script can be useful if you want to obfuscate your django project sources. I use the [pyobfuscate](http://freshmeat.net/projects/pyobfuscate/) tool, a little bit patched, the patch you can get [here](http://farid.adigamov.com/files/pyobfuscate.patch). The patch switchs off the classes and methods obfuscation as they could be imported from other files. The **pyobfuscate** util can obfuscate only one file at once. This script can obfuscate all .py files from the specified path (src_dir), at the end of the obfuscation it compiles them using **compileall** module. Set the **src_dir** and the **dst_dir** variables. Note: remove original **settings.py** and **urls.py** from the **src_dir** cause **pyobfuscate** util raises an error trying to encode them. The decorators are not handled correctly by pyobfuscate tool. I'm using django for about year and i didn't use the decorators except the '@transaction' decorators. I replace them from the sources at the beginning of the obfuscation and put them at their places in encoded file. In case of using other decorators you should make some changes in code ( line # 64 ).

  • obfuscate
  • sources
  • hide
  • obfuscator
Read More

ManyToMany field with newforms

In editing a ManyToMany field in a form, it is necessary to clear the entries in the bridge table before adding new entries. So first save the new entries, remove the old entries in the multiple choice field and then add the new entries. It is also necessary to add the commit_on_success decorator to make sure that the whole process is in one transaction.

  • newforms
  • multiplechoicefield
  • manytomany
Read More

Table of Contents

Simple template filter that extracts from a text ids, replaces '_' with spaces and produces hyperlinked Table of Contents. More info and usage example please see at [http://www.mysoftparade.com/blog/autogenerated-toc/](http://www.mysoftparade.com/blog/autogenerated-toc/)

  • toc
  • table-of-contents
Read More

Another means of updating a subset of a model's fields

Based on the UPDATE query section of `Model.save()`, this is another means of limiting the fields which are used in an UPDATE statement and bypassing the check for object existence which is made when you use `Model.save()`. Just make whatever changes you want to your model instance and call `update`, passing your instance and the names of any fields to be updated. Usage example: import datetime from forum.models import Topic from forum.utils.models import update topic = Topic.objects.get(pk=1) topic.post_count += 1 topic.last_post_at = datetime.datetime.now() update(topic, 'post_count', 'last_post_at') (Originally intended as a comment on [Snippet 479](/snippets/479/), but comments aren't working for me)

  • model
  • db
  • update
Read More

Select multiple using a manytomany checkbox

Usage: from yourapp.fields import CheckBoxManyToMany from django.db import models class Weekday(models.Model): name = models.CharField() def __unicode__(self): return self.name class EventWithWeekday(models.Model): weekdays = CheckBoxManyToMany(Weekday)

  • checkbox
  • multiple
  • oldforms
  • select
Read More

Update only selected model fields

Watch out! Previous versions of this snippet (without the values list) were vulnerable to SQL injection attacks. The "correct" solution is probably to wait until [ticket 4102](http://code.djangoproject.com/ticket/4102) hits the trunk. But here's my temporary fix while we wait for that happy day. Django's model.save() method is a PITA: 1. It does a SELECT first to see if the instance is already in the database. 2. It has additional database performance overhead because it writes all fields, not just the ones that have been changed. 3. It overwrites other model fields with data that may be out of date. This is a real problem in concurrent applications, like almost all web apps. If you just want to update a field or two on a model instance which is already in the database, try this: update_fields(user, email='[email protected]', is_staff=True, last_login=datetime.now()) Or you can add it to your models (see below) and then do this: user.update_fields( email='[email protected]', is_staff=True, last_login=datetime.now()) To add it to your model, put it in a module called granular_update, then write this in your models.py: import granular_update class User(models.Model): email = models.EmailField() is_staff = models.BooleanField() last_login = models.DateTimeField() update_fields = granular_update.update_fields

  • fields
  • model
  • save
  • performance
  • field
  • update
  • integrity
  • consistency
Read More

Recaptcha with Django Comments

Working off b23's [recaptcha support](http://www.djangosnippets.org/snippets/433/), I have hacked a way to add recaptcha support using existing comments. I am sure there is a better way, and ultimately I will suggest a patch to add captcha support as an option, but for now I hope this helps. For a more detailed rundown (as well as a working sample), check out my [blog entry](http://nikolajbaer.us/blog/recaptcha-django-free-comments/).

  • comments
  • recaptcha
Read More

sublist

*Usage:* `list|sublist:"a:b"` Returns `list[a:b]` Accepts `":b"` and `"a:"` shortcuts Note that the double quotes are necessary

  • filter
  • lists
  • templates
Read More

PreSaveMiddleware

With this middleware in place (add it to the MIDDLEWARE_CLASSES in your settings) you can pass a request to the model via a pre_save method on the model. I'm not sure if it is an improvement over the [threadlocals method] (http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser) but it may be an alternative that can be improved upon? class MyModel(models.Model): name = models.CharField(max_length=50) created = models.DateTimeField() created_by = models.ForeignKey(User, null=True, blank=True) def pre_save(self, request): if not self.id: self.created_by = request.user

  • middleware
  • pre_save
  • signals
Read More

self-related objects list with links

The problem was to output self-related objects (like category objects which may be a sub-category in any category and so on) in unordered list with links to certain view (providing some object.id arg). Its somewhat like unordered_list tag but takes plain list of objects and provides links. For example: category_list = Category.objects.all() In your template: {% related_linked_list category_list view_category %} This tag, however, have some limits: 1. Model shoud have self-related "parent" and id that may be passed into view. 2. In model parent = ForeignKey('self', ...) *related_name* is "child_set". But its simple enough that you may easily rewrite it for your own needs. :)

  • template-tags
  • output
Read More

Clouds Tag

This is a simple template tag to create Tag Clouds. Based on the number of Posts (change the model_name according to your schema), Tags are provided different size ( most number of posts => most popular => and hence the largest. We create a property called cloudsize for each tag, which is an integer between minsize and maxsize. Check the example of sample template use here http://www.djangosnippets.org/snippets/472/

  • tag
  • template-tag
  • tagging
  • clouds
  • cloud
Read More

Clouds Tag

This is a simple template tag to create Tag Clouds. Based on the number of Posts (change the model_name according to your schema), Tags are provided different size ( most number of posts => most popular => and hence the largest. We create a property called cloudsize for each tag, which is an integer between minsize and maxsize.

  • tag
  • template-tag
  • tagging
  • clouds
  • cloud
Read More

divShareApi

A python module for integration with http://www.divshare.com/integrate/api.

  • files
  • api
  • media
  • photos
  • divshare
  • video
Read More

2956 snippets posted so far.