Login

Most bookmarked snippets

Snippet List

Renderer decorator

You can use this as a decorator for your views, this way you can return a simple dictionary and the decorator will do the rest. **@TODO:** Automatically set the template based on the app/view request

  • shortcut
  • render
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

Manager for something like __inall

Provides the method from_related_ids, which lets you select some objects by providing a list of related ids (The huge difference to __in is that the objects have to match al of the ids, not only one) Model Example:: class Article(models.Model): text = models.TextField() tags = ManyToManyField('Tag') objects = AllInManager() Usage:: Article.objects.from_related_ids((1,2,3,4), 'tags')

  • model
  • db
  • manager
Read More

Sessions and authentication without cookies

[The Session documentation](http://www.djangoproject.com/documentation/sessions/) rightly warns of the dangers of putting a session ID into a query string. Sometimes, however, you have to do it - perhaps your client has mandated support for browsers with cookies disabled, or perhaps (as in my case) you're just dealing with a slightly broken client browser. This middleware pulls a session ID out of the query string an inserts it into the cookies collection. You'll need to include it in your MIDDLEWARE_CLASSES tuple in settings.py, *before* the SessionMiddleware. *Please* read my [full blog post](http://www.stereoplex.com/two-voices/cookieless-django-sessions-and-authentication-without-cookies) about for the dangers of doing this, and for full instructions and examples.

  • middleware
  • cookie
  • session
  • authentication
  • string
  • query
  • cookieless
  • querystring
Read More

Mako support as decorator

This snippet allows you to use @mako("templatename.mako") to define a mako template to use. Your python method just has to return a dictionary that will be passed to mako's context, after the addition of the "request" variable to the dictionary. If you return a non-False non dictionary object, it will return that instead of trying to render the template. The **request** variable is automatically added to the template's context. It also searches the current application's mako_templates/ subdirectory first before searching under the current directories mako_templates/, and does not use other application's mako_templates/ subdirectories at all. On Mako exceptions, it will display the Mako error page when debugging is enabled (hoping for extensible exception handling in the future to keep consistency) I got the idea from a [CherryPy tool](http://tools.cherrypy.org/wiki/Mako).

  • mako
Read More
Author: rmt
  • 2
  • 2

Handling choices the right way

This solves the problem with **choices** described [here](http://www.b-list.org/weblog/2007/nov/02/handle-choices-right-way/) Define your choices like this (in models.py): statuses = MyChoices(BIDDING_STARTED=10, BIDDING_ENDED=20) And then: status = models.IntegerField( default=statuses.BIDDING_STARTED, choices=statuses.get_choices() )

  • models
  • admin
  • choices
Read More

TruncateChars

**Usuage:** {{ comment.comment|truncatechars:20 }} **Why to use:** First of all, my english isn´t the best. I hope you will understand my text anyways :) Ok, I had a problem with some "kiddies" posting huge comments like "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaahhhhhhhhhhhhhhhhhhh this game rooooooooooocks!!!!!!!!!!!!!!!!". Django has no function to "kill" that huge words within a string. So I´ve coded this little peace and hope that someone could use it. Greets from Germany, Aveal http://www.onlinewars.eu

  • truncate
  • chars
Read More

improved getattr template filter

I tried to use [Joshua's](http://www.djangosnippets.org/users/joshua/) nice and very useful [getattr template filter (#38)](http://www.djangosnippets.org/snippets/38/), but ran into a few problems. I used it on objects outside of my control (admin internals, coughcough) and on some of them the code didn't catch the resulting exceptions. So I improved the error handling a bit. Furthermore, the code now also returns the *value of a callable* instead of the callable *itself* (last 4 lines). Looking at my code though, it can certainly be improved further.

  • template
  • filter
  • get
  • attr
Read More

Wiki-like markup for sub templates

I wanted to have the possibility to use a wiki-like markup style in my flatpages for various purposes (embedding images, quoting, etc.) After a few dead ends I came up with this, which is quite nice I think. > It basically takes a named tag, loads the corresponding template, passes in all arguments, renders the template and replaces the named tag with the result. *The markup looks like this:* > [[example:value to pass|option1=somevalue option2=values can have spaces too! without having to put them in quotes option3=some other value]] *This results in:* * Filter tries to load wiki/wiki_example.html * If it is loaded, it passes an WikiElement containing the value and the options to the template, renders it and replaces the tag with the rendered template *In the "wiki/wiki_example.html" template you can use it like this:* {{param.value}} {{param.opts.option1}} Or loop over param.opts.iteritems.

  • template
  • filter
  • markup
  • wiki
Read More

extras.py for management commands

! Note - no longer needed Save this script in the same directory as manage.py and run it through the command line. It picks up project Command class instances. Something that will hopefully be fixed in the Django SVN version soon. Heres an example of a command: #utils/management/commands/sqlallall.py from django.core.management import call_command from django.core.management.base import BaseCommand from django.db import models class Command(BaseCommand): help = "Returns sqlall for all installed apps." def handle(self, *args, **options): """ Returns sqlall for all installed apps. """ for app in models.get_apps(): call_command("sqlall", app.__name__.split(".")[-2])

  • management
  • commands
Read More

common model privacy

A BooleanField indicating privacy is common on models, but the name of the field and whether the field being True indicates private or public both may change across models. If there is more than one potentially private model, a common interface is needed. A commonly-named method would do the job with `[a for a in MyModel.objects.all() if not a.is_private()]`, but it would still retrieve private instances from the database only to filter them out. This approach puts the name of the privacy field and whether that field being True indicates private or public in a tuple attribute of the model class. A chainable method is added to all QuerySet objects. example use: class MyModel(models.Model): is_public = models.BooleanField(default=True) # ... privacy_field = ("is_public", False) \>\>\> publicMyModels = MyModel.objects.all().exclude_private() \>\>\> values = publicMyModels.values()

  • models
  • querysets
Read More

Default Template Loading

One of the things about Django that has always irked me is that there seems to be no standard facility for just loading a page and displaying it, simply. Yes, there is the flatpages module, but it is primarily designed for loading content from a DB. While you specify a custom template and put in junk values for the DB content, it just feels like extra, unnecessary work. Thinking about the problem some more, I borrowed from the idea of flatpages and implemented a view that will load an otherwise unmapped template off the filesystem and render it. This is very useful when converting an existing site over. Just copy your files over. No need to map anything in the URL conf or use the admin to add any flatpage entries. Since it'll render the template, too, you can even use tags and what not, so it need not be a static page.

  • template
  • loader
Read More

Db Mock

I hate when my unittest hits database. Especially when each test case needs different dataset. So I wrote this db mock, that's local to specific test and uses sqlite3 in-memory db. Usage (nosetests): class TestMainNoData(DbMock): 'testing main function with no meaningful data' def test_no_posts(self): 'there are no posts' assert models.Post.objects.count() == 0, 'should be no feeds'

  • testing
  • unittest
  • database
  • test
Read More

Javascript HTTP response

I've been using this along with [prototype](http://www.prototypejs.org) to make simple ajax calls. In essence you make the calls from the client with... new Ajax.Request('url',{parameters:{'someparam':$('someparam').value}}); return false; On the onsubmit event of a form, onclick or whatever. Note that the return false is important to prevent the page from reloading. Sending some javascript to be executed back to the client is then as simple as setting up your view to return: return HttpJavascriptResponse('alert("boing");') So, yeah, prototype does the real work and this class does little other than make it clear what our intentions are and reduce the opportunities for typos. But it works for me.

  • ajax
  • javascript
  • prototype
  • return
Read More

3110 snippets posted so far.