Login

Top-rated snippets

Snippet List

paginator using url tag

Example for provided django-tagging url snippet: {% paginator 4 image_tag_paged tag=tag page %} links then equals {% url image_tag_paged tag=tag,page=n %}

  • tag
  • pagination
  • url
  • paginator
Read More

page_link

To make page links like below: Prev 1 ... 23 24 25 26 27 ...221 Next Use like this , "bbs_posting_list" is the name of url {% page_link "bbs_posting_list" page pages %}

  • page
Read More

Template tag to sort a list of links

Sorts a list of HTML anchor tags based on the anchor's contents. This is useful, for example, when combining a static list of links with a dynamic list that needs to be sorted alphabetically. It ignores all attributes of the HTML anchor. {% load anchorsort %} {% anchorsort %} <a href="afoo.jpg">Trip to Fiji</a> <a href="bfoo.jpg">Doe, a deer, a female deer!</a> {% for link in links %} <a class="extra" href="{{ link.href|escape }}">{{ link.name|escape }}</a> {% endfor %} {% endanchorsort %} Note that case (capital vs. lower) is ignored. Any HTMl within the node itself **will not be removed**, so sorting `<a>Bar</a><a><strong>Foo</strong><a/>` will sort as `<a><strong>Foo</strong></a><a>Bar</a>` because `<` is logically less than `b`.

  • template
  • sort
  • anchor
  • a
Read More

Using descriptors for lazy attribute caching

Python's [descriptor][1] protocol can seem a bit esoteric at first; however, it can be invaluable in handling everyday idioms and patterns - something that the Django framework authors have taken advantage of in numerous occasions (e.g.: [auth middleware][2]). One such idiom I see and use often and would like to generalize is the attribute-existence check-or-set routine illustrated here: def get_foo(self): if not hasattr(self, '_foo'): self._foo = init_foo() return self._foo Rather than coding this up multiple times (either for a given class or across many unrelated classes), I would prefer to delegate this repetitive work to a descriptor and remain [DRY][3]. The means to this end is implemented as a variation on the Python `property` construct, and is intentionally over simplistic (I leave the details of the heavy lifting up to the reader). The basic premise shown in source here is simply straight-forward Python, a quick and dirty example of how it could be utilized within a Django context is shown here: from django.db import models from cacheprop import CacheProperty2 ARTIFACT_TYPES = ( ('F', _('File')), ('D', _('Directory')), ('A', _('Alias')), ) class Artifact(models.Model): # model fields name = models.CharField(maxlength=64) type = models.CharField(maxlength=1, choices=ARTIFACT_TYPES) file_metadata = CacheProperty2( lambda self: self.filemetadata_set.get(artifact__id=self.id) ) class FileMetadata(models.Model): byte_size = models.IntegerField() artifact = models.ForeignKey(Artifact, unique=True) [1]: http://users.rcn.com/python/download/Descriptor.htm [2]: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/middleware.py [3]: http://c2.com/cgi/wiki?DontRepeatYourself

  • python
  • descriptors
Read More

Automatic Paragraphs

I just converted the autop filter from Drupal (which is itself based on a Wordpress filter) from PHP to Python. I had to change the format of the regular expressions a bit and make them raw strings, but otherwise the function is unchanged. It should work exactly like the original function.

  • filter
  • text
  • format
Read More

sqlallall.py

A simple script to run 'manage.py sqlall' on every app in a project.

  • sql
  • manage.py
  • sqlall
Read More
Author: jkl
  • 0
  • 2

Pass db.Field to newforms.Widget

Deprecated. I don't use this any more. Hi, I want decimal input which uses a comma as decimal seperator. It was quite complicated, but it works. It can be used as an example how to create an own subclass of an existing db.Field class and how to pass the dbfield to the widget, and use it in its render() method. I think my snippet is too complicated, but couldn't find a better solution. If you do, please tell me.

  • newforms
  • i18n
Read More

"Approved" field with timestamp

I wanted to make the objects of a particular model approvable and store the timestamp of when that happened. In other frameworks/languages, I used to combined those in one "approved_at" field, which would be NULL if an object was currently unapproved. I tried different approaches to implement this in django, and this is the best I came up with so far. Basically, the code in __setattr__ makes sure that the field, once set, will not be updated again. Overriding setattr__() could also be a solution to determining if a field value has changed in save(), a question that seems come up from time to time in #django.

  • newforms
  • models
  • fields
  • forms
  • save
Read More

Random code tag

This tag solves for me a simple need: generate random and compact codes for some of my applications. Codes are not guaranteed to be unique. **Usage** {% randomCode "num" %} **Example**: {% randomCode "8" %} generates a random 8 characters code. Create a file on your favorite template tags folder called randomcode.py and paste the code. Don't forget to include {% load randomcode %} in your templates

  • tag
Read More

linebreaksli template filter

This template filter will split a string of text on newlines and return a string of <li></li>s with a newline before every line. This is handy for taking a paragraph of text and making an <ol> or <ul> from its lines. Don't forget to register your filter with the template library first or the filter won't work.

  • filter
  • linebreaks
  • li
Read More

Send information mails to related staff members.

You can use this method to send information mails to the related staff members about section specific site activity. All users which explicitly permitted to 'change' given object will be informed about activity. If you defined get_absolute_url in your model then you can simply use it like this; ` obj=form.save() mail2perm(obj) ` Or you can define your custom urls ; ` from util.mail2perm import mail2perm,domain reply=get_object_or_404(Reply,user=request.user,pk=id) mail2perm(reply,url='http://%s/admin/support/show/?id=%s'%(domain,reply.id)) `

  • mail
  • permission
Read More

E-mail quoting filters and tags

Ttemplates and filters for quoting e-mails in templates. The `quoted_email` tag takes a template, renders it and quotes the result. The `quote_text` filter puts one or more levels of quotes around the passed text.

  • filter
  • tag
  • filters
  • email
  • tags
  • quoting
Read More

Forcing unit test runner to abort after failed test

Sometimes running a test suite can take a long time. This can get especially annoying when you see a failure or error, but have to wait for all the remaining tests to run before you can see the relevant stack traces. Pressing ctrl+c to interrupt the tests does not work; the KeyboardInterrupt exception does not get caught and only a stack trace irrelevant to your tests is produced. This behavior can be altered through overriding the testcase's `run` method and catching the exception yourself. Now you can stop the tests whenever you want to and still see what is wrong with your tests.

  • unit-test
Read More

3110 snippets posted so far.