Login

Top-rated snippets

Snippet List

Searchable Media

This app allows you to utilize mysql's fulltext searching over multiple models and multiple apps, letting the site search seem more intuitive, yet still allow your content to be very structured. Essentially, it creates an entire new model that associates objects to a chunk of text to search efficiently over (and index), using the contenttypes app. Simply add the post_save events to your existing models for things you want to be searched.

  • search
  • media
  • fulltext
  • mixed
Read More

unique validation for ModelForm

Inherit your forms from model from this ModelForm and it will check all the database fields with unique=True in `is_valid()`. This is a hack around [#5736](http://code.djangoproject.com/ticket/5736). It is actually a part of a grand problem mentioned in [#4895](http://code.djangoproject.com/ticket/4895). You can use this hack until the issue is fully resolved.

  • newforms
Read More

djangoskel

Sometimes i like to try things out in a blank django project, so i created a python script which creates an out of the box working project skeleton for me: $ djangoskel.py project_name

  • project
  • skeleton
Read More

Q marshaller

Django supports the serializing model objects, but does not support the serializing Q object like that, ============================ q = Q(username__contains="findme") model0.objects.filter(q) serialize(q) # X ============================ so I wrote a little marshaller for Q, this is example, ============================ from django.contrib.auth import models as django_models qs = django_query.Q(username__contains="spike") | django_query.Q(email__contains="spike") _m = QMarshaller() a = _m.dumps(qs) # a was serialized. When call the similiar queries in page by page, you don't need to write additional code for creating same Q(s) for filtering models, just use the serialized Q as http querystring and in the next page unserialize and apply it. That is simple life.

  • model
  • python
  • q
  • query
Read More

Augmented TimeField

A TimeField that lets you parse a wide variety of freeform-text time descriptions. This doesn't inherit from TimeField because it doesn't use any of its functionality. Includes unit tests demonstrating some examples of what the parser will and won't handle.

  • newforms
  • timefield
Read More

Lazily lookup dynamically for templates

If you've ever wanted to dynamically lookup values in the template layer (e.g. `dictionary[bar]`), then you've probably realized/been told to do this in the python layer. The problem is then you often to build a huge 2-D list to hold all of that data. These are two solutions to this problem: by using generators we can be lazy while still making it easy in the python layer. I'm going to write more documentation later, but here's a quick example: from lazy_lookup import lazy_lookup_dict def some_view(request): users = User.objects.values('id', 'username') articles = Article.objects.values('user', 'title', 'body') articles = dict([(x['user'], x) for x in articles]) return render_to_response('some_template.html', {'data': lazy_lookup_dict(users, key=lambda x: x['id'], article=articles, item_name='user')}) Then in the template layer you'd write something like: {% for user_data in data %} {{ user_data.user.username }}, {{ user_data.article.title }} {% endfor %}

  • template
  • dynamic
  • lookup
  • lazy
  • dynamic-lookup
Read More

Scoped Cache Compatible with Django Caching Helpers

Have you ever felt the need to run multiple Django projects on the same memcached server? How about other cache backends? To scope the cache keys, you simply need to prefix. However, since a lot of Django's internals rely on `django.core.cache.cache`, you cannot easily replace it everywhere. This will automatically upgrade the `django.core.cache.cache` object if `settings.CACHE_PREFIX` is set to a string and the Middleware contains `ScopeCacheMiddleware`. A thread discussing the merging of this functionality into Django is available on [the dev mailing list](http://groups.google.com/group/django-developers/browse_thread/thread/d45edaafec56da2a). However, (as of now) nowhere in the thread does anyone mention the reason why this sort of treatment is needed: Many of Django's internal caching helpers use `django.core.cache.cache`, and will then conflict if multiple sites run on the same cache stores. Example Usage: >>> from django.conf import settings >>> from django.core.cache import cache >>> from scoped_caching import prefix_cache_object >>> settings.CACHE_PREFIX 'FOO_' # Do this once a process (e.g. on import or Middleware) >>> prefix_cache_object(settings.CACHE_PREFIX, cache) >>> cache.set("pi", 3.14159) >>> cache.get("pi") 3.14159 >>> cache.get("pi", use_global_namespace=True) >>> cache.get("FOO_pi", use_global_namespace=True) 3.14159 >>> cache.set("FOO_e", 2.71828, use_global_namespace=True) >>> cache.get("e") 2.71828 To Install: Simply add `ScopeCacheMiddleware` as a middleware and define `settings.CACHE_PREFIX` and enjoy!

  • middleware
  • cache
  • namespace
Read More

smart spaceless

Just like `{% spaceless %}`, except a single space is preserved between two inline tags (such as `<a>`, `<em>`, and so on). This lets you use the tag on running text without fear of running two spans of styled text together incorrectly.

  • tag
  • spaceless
Read More

Manager introspecting attached model

[A comment on a recent blog entry of mine](http://www.b-list.org/weblog/2008/feb/25/managers/#c63422) asked about a setup where one model has foreign keys pointing at it from several others, and how to write a manager which could attach to any of those models and query seamlessly on the relation regardless of what it's named. This is a simple example of how to do it: in this case, both `Movie` and `Restaurant` have foreign keys to `Review`, albeit under different names. However, they both use `ReviewedObjectManager` to provide a method for querying objects whose review assigned a certain rating; this works because an instance of `ReviewedObjectManager` "knows" what model it's attached to, and can introspect that model, using [Django's model-introspection API](http://www.b-list.org/weblog/2007/nov/04/working-models/), to find out the correct name to use for the relation, and then use that to perform the query. Using model introspection in this fashion is something of an advanced topic, but is extremely useful for writing flexible, reusable code. **Also**, note that the introspection cannot be done in the manager's `__init__()` method -- at that point, `self.model` is still `None` (it won't be filled in with the correct model until a bit later) -- so it's necessary to come up with some way to defer the introspection. In this case, I'm doing it in a method that's called when the relation name is first needed, and which caches the result in an attribute.

  • managers
  • models
  • introspection
Read More

cache_smart template tag

cache_smart template tag is a drop in replacement for default cache tag by Django but with the added bonus to be more resistant against dog-pile/stampeding effect. This snippet uses a extra cache entry to store a stale time so we don't have to pickle/unpickle to store this extra value. If this cache entry returns None, as in expired it will reset the stale timeout 30 seconds in the future so further calls will just return the old value while this request is regenerating the new value. **warning** Don't use both cache template tags!

  • template
  • cache
  • memcached
Read More

Colorize Filter

I had a need to colorize the nicks for the new DjangoBot Logger. Instead of managing a collection of names and corresponding colors we decided it would be more simple to just "hash" the nickname using a colorize filter. This causes the same nickname to always appear in the same color.

  • filter
  • colorize
Read More

Table Creation Using ORM Standalone

I love the Django templates and ORM, but I prefer to use CherryPy as my web server. So I want to be able to do the equivalent of "python manage.py sql" but without actually needing to have a Django application. So I stick all of my models in a file named "models.py" and then run this script and it prints out all of the CREATE TABLE statements for my database.

  • orm
Read More

Logging and statistic middleware

Reviewing some statistic-middleware-classes I think you might need one wich is working correct and high-performant. Please comment it and have fun with it!

  • middleware
  • stats
  • logging
  • statistic
  • user-activities
Read More

3110 snippets posted so far.