Login

All snippets written in Python

Snippet List

ifinlist template tag

I recently had to write a custom template tag which checks to see if a value exists in a list variable from within a Django template. This was my first ever attempt at writing a template tag so any feedback would be appreciated.

  • template-tag
  • if-in-list
  • if-value-in-list
Read More

Play nice with ModelAdmin mixins

There are several nice ModelAdmin subclasses that provide useful functionality (such as django-batchadmin, django-reversion, and others), but unfortunately a ModelAdmin can really only subclass one at a time, making them mutually exclusive. This snippet aims to make mixing these classes in as easy as possible -- you can inherit your model admin from it, add a tuple of mixins, and it will dynamically change the inheritance tree to match. This isn't guaranteed to work with all ModelAdmins, but so long as the mixins play nice with django modeladmin they *should* work.

  • mixin
  • modeladmin
Read More

Media Wiki With mwlib

### Simple wiki with MediaWiki and Markdown Support Once you install the mwlib you can use mwit to convert Mediawiki markup to HTML. I am include the model that uses it to hopefully provide a good example. I maintain a version and only one copy of each wiki entry in the main table and archive replaced markup into another table, you will need to create the archive model or remove that section of code. The line ending changes in mwit are so that it will work with IE.

  • markup
  • markdown
  • mediawiki
  • wiki
  • archive
Read More

User from session key

This blog post outlined how to get the user from the session key: http://scottbarnham.com/blog/2008/12/04/get-user-from-session-key-in-django/ Unfortunately, it assumes DB-backed session and auth backends. This isn't required, so this snippet provides a backend-agnostic way to do the same thing. >>> skey = 'ea0ed02d35d43aeaf20b3ef516f51396' >>> user_from_session_key(skey) <User: jeremyd>

  • session
  • user
  • auth
Read More

UnicodeReprMixIn

Add's updated and created fields to a model if mixed in. Example that uses the name as the representation: class Company(models.Model, UnicodeReprMixIn): """ A representation of a comic book company. """ name = models.CharField(max_length=255) slug = models.SlugField() logo = models.ImageField(upload_to=os.path.join('upload', 'company_logos')) url = models.URLField(verify_exists=True) _unicode = "name"

  • model
  • unicode
  • orm
  • mixin
  • __unicode__
Read More

AddThis Social Networking TemplateTag

Code to add an 'AddThis' button to your blog posts. Simply do: {% add_this post.title post.get_absolute_url %} Also, specify your ADD_THIS_USERNAME to your settings. <!-- blog/add_this.html --> <script type="text/javascript">var addthis_pub="{{ username }}";</script> <a href="http://www.addthis.com/bookmark.php" onmouseover="return addthis_open(this, '', '{{ site.domain }}{{ url }}', '{{ site.name }} - {{ title }}')" onmouseout="addthis_close()" onclick="return addthis_sendto()"> <img src="http://s7.addthis.com/static/btn/lg-addthis-en.gif" width="125" height="16" border="0" alt="" style="border:0"/></a> <script type="text/javascript" src="http://s7.addthis.com/js/152/addthis_widget.js"></script>

  • template-tag
  • add-this
  • social-networking
Read More

Lazy options on ModelForm fields - like setting a ModelChoiceField queryset from the view

Example view code: lazy_field_options = { 'field_name_that_is_m2m': { 'queryset': YourRelatedModel.objects.filter(groups=request.user.groups.all()), }, 'field_name_that_is_fk': { 'queryset': YourOtherRelatedModel.objects.filter(slug=request_slug), }, } modelform = YourModelForm(jpic_field_options=lazy_field_options) # after the modelform has called for parent __init__, it will set # options for each field if possible.

  • hack
  • form
  • queryset
  • modelchoicefield
  • modelform
  • modelmultiplechoicefield
Read More

Clone model mixin

Add this as a superclass of any Django model to allow making copies of instances of that model: class Entry(models.Model, CloneableMixin): [...] e = Entry.objects.get(...) e_clone = e.clone() e_clone.title = 'Cloned Entry' e.save() The new object is saved during the clone process and ManyToMany relations are copied as well.

  • model
  • mixin
  • copy
  • clone
  • clonable
Read More

Null Field Admin Filter

This patch adds a new admin Filter, for Filtering nullable fields. It adds 3 possible choices: 'All' (no filter), 'Null' (it applies field__isnull=True filter), and 'With Value' (it filters null values). This patch is interesting when you have a Integer or String fields and you want to filter wether a value is set or not. In other case, it would show too many filtering options. Remember this is a patch and you must modify a django file in `django/contrib/admin/filterspecs.py`

  • filter
  • admin
  • null
Read More

Image resize on demand

** Image on demand view ** I often post photos on photography fora. Most fora want you to place a link to a photo somewhere on the net, but different fora have different rules. Some fora want you to stick to a maximum of 800 pixels wide, some 700 pixel and some even strange values like 639 pixels. My own site uses 600 pixels so I end up resizing images all the time. Since I keep my originals with my gallery as well (hidden for public viewing) resizing on the fly would be a nice asset. I'm using my previous snippet to apply a slight unsharp mask for better web display of my photos. ** usage ** This snippet takes the url to my photo application which is a simple link using the pk of my photo table and adds 'width'.jpg to the end (some fora check if the link is an image based on extenstion) The view takes the width requested and creates the resized image from the original full size image or takes it from the cache for display on demand. To prevent a dozen directories I use a setting to specify which widths are allowed, providing room for several versions of the same image. Any improvements are appreciated since I'm still rather inexperienced in Python and Django.

  • image
  • pil
  • resize
  • pythonmagick
Read More

Unsharp Mask with PIL and PythonMagick

**A Magick PIL** I used to do my image conversions with ImageMagick and system calls back in my PHP days. With Django PIL is the obvious choice for most image stuff, but frustrated by the lack of a proper unsharp mask function for PIL I found some code in the bits and pieces of documentation for PythonMagick. (yes I know, Kevin Cabazon wrote PIL_usm, but I could not get it to work, probably due to my inexperience. Anyway, this code makes it easy to convert back and forth from PIL to PythonMagick (maybe not such a good idea on a memory tight high loaded production server, but no problem on my private server (Pentium-M @ 1.8 Ghz with 1 GB Mem.) **usage:** usm takes a PIL image object. Radius and sigma is in pixels, amount 1 compares to 100% in photoshop, threshold 0.004 ~ (1/256) compares to 1 in photoshop: I'm using r=1,s=0.5,a=0.8,t=0.016 for roughly 800x600 images created from 3000x2000 (6MP) images. Experiment for your own preferences.

  • image
  • pil
  • sharpen
  • thumbnails
  • pythonmagick
  • usm
Read More

Links with XFN (and Validation)

Slightly different validation to that of jpwatts; developed with knowledge of that snippet but written up from scratch for use as a fallback for when the Javascript Assist is off. I'm no master programmer, so feedback/comments/criticism is more than welcome. The accompanying Javascript (xfn-admin.js) can be found here: [http://www.djangosnippets.org/snippets/1266/](http://www.djangosnippets.org/snippets/1266/).

  • xfn
  • microformats
Read More

ModelForm ExtJS JSON Encoder

from http://www.djangosnippets.org/snippets/792/ from utils.extjs import ExtJSONEncoder from django.utils.safestring import mark_safe class TestForm(forms.ModelForm): class Meta: model = TestModel def as_ext(self): return mark_safe(simplejson.dumps(self,cls=ExtJSONEncoder))

  • json
  • modelform
  • extjs
Read More

2955 snippets posted so far.