Login

Most bookmarked snippets

Snippet List

Monkey-patch Django's test client to return WSGIRequest objects

Testing low-level functionality sometimes requires a WSGIRequest object. An example of this is testing template tags. This will monkey-patch the test Client object to return WSGIRequest objects Normal Django behavior: >>> client.get('/') <HttpResponse > With this code, get the request object: >>> client.request_from.get('/') <WSGIRequest > Installation: For this to work, you simply need to import the contents of this file. If you name this file `clientrequestpatch.py`, do this inside your Django tests. from django.test.testcases import TestCase from myproject.test import clientrequestpatch

  • request
  • test
  • client
  • wsgi
  • wsgirequest
Read More

Analogue template filter to removetags that also removes the content of the tag

Django's builtin `removetags` filter removes the supplied tags, but leaves the enclosed text alone. Sometimes you need the complete tag, including its content to go away. Example: <h1>Some headline</h1> <p>Some text</p> Applying `removetags:"h1"` to this html results in Some headline <p>Some text</p> while `killtags:"h1"` leaves <p>Some text</p>

  • filter
  • removetags
Read More

Allow any view (probably a generic view) to accept POST variables into extra_context

Supposing you wanted to use a generic view, but you wanted to pass something over POST to show up in the resultant template. Perhaps you're creating a new object, and you want to pre-populate some hidden fields. `urlpatterns = patterns('django.views.generic.create_update', url(r'^obj/new$', view_post_vars_to_context(create_object), {'form_class': ThingForm, 'template_name': 'thing/new_thing.html', 'post_vars_to_context':{'obj_id':'objID'}, extra_context: {:this":"that"}}), )` Now objID will be a variable in your template, with the value passed via POST in the variable obj_id. This is good for generic views, but there's no reason you couldn't use it for your own views if you really wanted, as long as you had an "extra_context" parameter. For security, since POST variables aren't cleansed automatically, this only accepts values of "_" and "-". If you feel confident, you can alter this to your needs.

Read More

MoinMoin auth backend

This snippet implements an authentication backend for MoinMoin user accounts. If you have a MoinMoin running on the same server which has users, you can allow those users to sign into a Django site with the same username and password. To use, define the following settings: MOIN_DATA_DIR = "/path/to/moinmoin/data/dir" AUTH_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', '<this snippet module>.MoinMoinBackend', ) # optional list of groups that authenticating users must be in MOIN_AUTH_GROUPS = ["EditorGroup",]

  • auth
  • backend
  • moinmoin
Read More

Initially open collapsable fieldset class in admin

It's just an extension for the admin. Replace the collapse.js (collapse.min.js) and use it like this in the admin fieldset option: ´´**'classes': ['collapse', 'open']**´´. Without the 'open'-class, it will work as usual. *Needs possibly fixing for IE <= 8* because IE doesn't support the ´´:not´´ selector.

  • fieldset
  • collapse
  • collapsed
  • open
  • show
Read More

Parse custom template tag's args or kwargs

Enhanced version of snippet [1113](http://djangosnippets.org/snippets/1113/) Usage example (not self-contained): @register.tag def groupurl(parser, token): ''' Syntax:: {% groupurl view_name group [key=val, [key=val, ...]] [as varname] %} Example:: <a href="{% groupurl blog_detail group slug=blog.slug %}">{{ blog.name }}</a> ''' bits = token.contents.split() tag_name = bits[0] if len(bits) < 3: raise template.TemplateSyntaxError("'%s' takes tag at least 2 arguments (path to a view and a group)" % (tag_name,) bits_iter = iter(bits[1:]) # view_name + group and url kwargs args, kwargs = parse_args_and_kwargs(parser, bits_iter, stop_test='as', tagname=tag_name) if len(args) != 2: raise template.TemplateSyntaxError("'%s' takes exactly two non-kwargs (path to a view and a group)" % (tag_name,)) view_name, group = args # as var asvar = None for bit in bits_iter: asvar = bit return GroupURLNode(view_name, group, kwargs, asvar)

  • tag
  • templatetag
  • parse
  • args
  • kwargs
Read More

slug_and_slash_to_dash - modified slugify for urls

This filter converts slashes to spaces in a a sting and then slugify's the result. However, it ignores leading and trailing slashes. For example, it can take something like this: /some/url/with-an-existing-slug/ And turn it into this: some-url-with-an-existing-slug The filter was originally written to use the *curent* url as the `disqus_identifier` for Disqus comments. For example: {{ request.META.PATH_INFO|slug_and_slash_to_dash }}

  • template
  • filter
  • slugify
Read More

Testing for failure in management commands

Because BaseCommand catches all CommandError exceptions and turns them into nicely formatted strings before calling sys.exit(1), it can be tricky to properly test failure. Normally, this is great, but it makes testing that a command fails when we expect to a little harder. That's where this snippet comes in. It redirects sys.stderr to an instance StringIO where we can monitor what's output and catches the BaseException raised by sys.exit(1). Form here, it's trivial to test that a management command fails exactly as you'd expect it to.

Read More

mkrange - create a range() inside a template - variable/filter support for range values

Ok, I just took [wolever](http://djangosnippets.org/users/wolever/)'s snippet at [http://djangosnippets.org/snippets/1926/](http://djangosnippets.org/snippets/1926/) and added template variable/filter support for range values. For instance, you could write something like this: `{% mkrange 1 tool_page.paginator.num_pages|add:"1" as page_range %}` I'm just learning python and django, so any advice would be appreciated.

  • django
  • python
  • custom tag
Read More

RadioSelectWithHelpText

A Django form widget which displays help text for individual items in a set of radio buttons. It overrides the RadioSelect widget, adding a small bit of HTML after each <input> element, with the help text for each item. It was developed for a Django Dash project I'm working on (called transphorm.me), so isn't as feature-rich as it could be, but if you have any trouble installing it - or if I've miscopied any of my code in my rush - please let me know.

  • newforms
  • forms
  • widgets
  • radioselect
Read More

comments_allowed function for your model/...

Use this if you want to check if commenting is allowed for a certain object/model/... in a template. Like this; `{% if not object.comments_allowed %} <p>Comments are now closed.</p> {% else %} {% render_comment_form for object %} {% endif %}` You can replace the CommentModerator class with your own custom moderation class ofcourse.

  • comments
  • moderation
Read More

3110 snippets posted so far.