Login

3110 snippets

Snippet List

Pretty Paginator Tag

This is a modified version of the (http://djangosnippets.org/snippets/73/) paginator snippet. It works with the django paginator.

  • paginator
  • 'digg style'
Read More

template filter to include protocol and domain in absolute urls

I created this template filter to be able to use get_absolute_url in an email template. Save the code into /templatetags/navigation.py Use like this: {% load navigation %} {{ instance.get_absolute_url|siteabsoluteurl:request }}

  • template
  • filter
  • templatetag
  • template-filter
  • url
  • template-filters
  • get_absolute_url
  • templatefilter
  • absolute
Read More

RegEx redirect fallback middleware

Simple middleware to complement the built in redirect middleware app. Add this after the contrib.redirect middleware - this will be fired if a 404 is triggered and the contrib.redirect fails to find a suitable redirect. Useful if you want to add the redirects into the DB - and/or don't have access to the .htaccess script or whatever HTTP server based redirect machinery your site runs off. You simply add in regex 'old_path' and 'new_path' entries into the same redirect app, but this will try to do a regex find and replace - i.e. >>> r = new Redirect() >>> r.old_path = '/my/test/path/([a-z]+)/with/regex/' >>> r.new_path = '/my/result/path/$1/with/regex/' >>> r.save() this will convert: /my/test/path/abcdef/with/regex/ into: /my/result/path/abcdef/with/regex/' also works with query strings: /index.php?section=products >>> old_path = '/index.php/\?section=([a-z]+)' #need to add in the forward slash if ADD_SLASHES = True in your settings, and escape the question mark. >>> new_path = '/section/$1/' converts the url to '/section/products/'

  • regex
  • Redirect
  • /
Read More

MintCache (simple version)

This is intended as an alternative to http://www.djangosnippets.org/snippets/155/ Put this in your own cache.py and import it instead of django.core.cache and use it the same way. We left out the "add" function but it shouldn't be too hard to make if you want it. From the above post: "The purpose of this caching scheme is to avoid the dog-pile effect. Dog-piling is what normally happens when your data for the cache takes more time to generate than your server is answering requests per second. In other words if your data takes 5 seconds to generate and you are serving 10 requests per second, then when the data expires the normal cache schemes will spawn 50 attempts a regenerating the data before the first request completes. The increased load from the 49 redundant processes may further increase the time it takes to generate the data. If this happens then you are well on your way into a death spiral MintCache works to prevent this scenario by using memcached to to keep track of not just an expiration date, but also a stale date The first client to request data past the stale date is asked to refresh the data, while subsequent requests are given the stale but not-yet-expired data as if it were fresh, with the undertanding that it will get refreshed in a 'reasonable' amount of time by that initial request."

  • cache
  • memcached
  • caching
  • mintcache
Read More

Smart i18n date diff (twitter like)

This snippet display a human readable date diff. You give it the your date in parameter and the diff with datetime.datetime.now() is returned. The diff must be positive to be more accurate (future dates are not supported) Usage: {{ status.created_at|date_diff }} Will give something like: less than 1 minute ago 13 minutes ago 1 hour ago etc. Based on [Fuzzy Date Diff Template Filter](http://www.djangosnippets.org/snippets/1347/)

  • datetime
  • i18n
  • date
  • diff
Read More

Flickr Sync

This code provides a Django model for photos based on Flickr, as well as a script to perform a one-way sync between Flickr and a Django installation. *Please note that the snipped contains code for two files, update.py and a Django model.* *The two chunks are separated by:* """ END OF FLICKRUPDATE """ """ START DJANGO PHOTO MODEL Requires django-tagging (http://code.google.com/p/django-tagging/) """ My model implements tagging in the form of the wonderful django-tagging app by Jonathan Buchanan, so be sure to install it before trying to use my model. The flickrupdate.py code uses a modified version of flickerlib.py (http://code.google.com/p/flickrlib/). Flickr returns invalid XML occasionally, which Python won't stand for. I got around this by wrapping the return XML in `<flickr_root>` tags. To modify flickrlib to work with my code, simply change the this line: return self.parseData(getattr(self._serverProxy, '.'.join(n))(kwargs)) to: return self.parseData('<flickr_root>' + getattr(self._serverProxy, '.'.join(n))(kwargs) + '</flickr_root>') I hate this workaround, but I can't control what Flickr returns. flickrupdate will hadle the addition and deletion of photos, sets and tags. It will also keep track of photos' pools, although, right now, it doesn't delete unused pools. This is mostly because I don't care about unused pools hanging around. It's a simple enough addition, so I'll probably add it when I have a need. Be sure to set the appropriate information on these lines: api_key = "YOUR API KEY" api_secret = "YOUR FLICKR SECRET" flickr_uid = 'YOUR FLICKR USER ID' I hadn't seen a Django model and syncing script, so I threw these together. I hope they will be useful to those wanting start syncing their photos.

  • flickr
  • photos
  • photo
  • flicker
Read More

Model inheritance with content type and inheritance-aware manager

inspired by crucialfelix's [inheritance hack](http://www.djangosnippets.org/snippets/1031/), which was a far better method of fetching a model's subclassed version from an instance than my own, i decided to bake his snippet in to my own inheritance hack, which i think benefits both. the result is a query set that returns subclassed instances per default. So - in the snippet's example, querying `Meal.objects.all()[0]` will return a salad object, if that instance of Meal happens to be the parent of a Salad instance. To my mind this is closer to the 'intuitive' way for a query set on an inheriting model to behave. **Updated:** added subclassing behaviour for the iterator access as well. **Updated:** incorporated carljm's feedback on inheritance

  • manager
  • inheritance
Read More

ParentModel and ChildManager for Model Inheritance

This is the approach I've taken to access instances of child models from their parent. Functionally it's very similar to snippets [1031](http://www.djangosnippets.org/snippets/1031/) and [1034](http://www.djangosnippets.org/snippets/1034/), but without the use of `django.contrib.contenttypes`. Usage: class Post(ParentModel): title = models.CharField(max_length=50) objects = models.Manager() children = ChildManager() def __unicode__(self): return self.title def get_parent_model(self): return Post class Article(Post): text = models.TextField() class Photo(Post): image = models.ImageField(upload_to='photos/') class Link(Post): url = models.URLField() In this case, the `Post.children` manager will return a queryset containing instances of the appropriate child model, rather than instances of `Post`. >>> Post.objects.all() [<Post: Django>, <Post: Make a Tumblelog>, <Post: Self Portrait>] >>> Post.children.all() [<Link: Django>, <Article: Make a Tumblelog>, <Photo: Self Portrait>]

  • model
  • manager
  • queryset
  • inheritance
Read More

Cache Backend using memcached including prefix settings

Django later than 1.3 (not sure of exact version) wasn't using prefix settings in cache tags or functions used in views. Just for whole page caching. This is small custom cache snippet based on memcached.CacheClass. Feel free adding any comments.

  • memcache
  • cache
  • memcached
  • cache-backend
  • prefix
Read More

Digg-style pagination, and retain GET params

This snipplet is based on [Ryan Kanno's work](http://blog.localkinegrinds.com/2007/09/06/digg-style-pagination-in-django/) and [snipplet #2680](http://djangosnippets.org/snippets/2680/). The page numbers are basically composed by `pages_outside_trailing_range`, `page_range` and `pages_outside_leading_range`. The GET params in the request(except for `page` itself) are retained across different pages. This is important when you have an `order_by` param working inline.

  • pagination
Read More

IsNullFieldListFilter

As the title does a pretty good job of condensing, this is a subclass of `FieldListFilter` for the Django 1.4 Admin system which allows you filter by whether a field is or is not `NULL`. For example, if you had an `Author` model and wanted to filter it by whether authors were also users of the site, you could add this to your `AuthorAdmin` class: list_filter = ( ('user_acct', IsNullFieldListFilter), ) For the record, it began life as a modified version of `BooleanFieldListFilter` from `django.contrib.admin.filters`.

  • filter
  • django
  • admin
  • fieldlistfilter
Read More

add port from settings file to an url

I'm working on a Project where on certain places I need absolute URL's, in development mode I need the port 8000 added to any absolute url. This piece of work, took me some time to figure out. Couldn't find something similiar on the net, it's based on Code from the Python urlparse module. You can change the "settings.PORT" part to "settings.DEBUG == True" if you like, and so on. META: replace parameters in URL, edit parameters in URL, edit URL, urlparse

  • url
  • urlparse
  • port
  • replace-parameters-in-url
  • urlsplit
Read More

Handles Inline Formsets and also "in-standard-way" normal forms

If you read the docstring and the example you should get a clue what this Code does. I didn't want a big function everytime that handles every specific form, formset combinations so this how i can add/edit Models with specific Forms given to the magic_handle_inlineformsets function. It also works for Forms without innline_formsets.

  • forms
  • formset
  • inline
  • inlineformset
  • inline_formset
Read More