Login

Most bookmarked snippets

Snippet List

Email on new comments

In response to [#366](/snippets/366/), this is a subclass of the `CommentModerator` class from `comment_utils` which does nothing except email the "owner" of an object whenever a new comment is posted on it; all other moderation options remain inactive.

  • email
  • comments
Read More

Repeat blocks with new context / simple Jinja-like macro system

A simple macro system that makes it possible to reuse previously defined blocks, optionally with a custom context, similar to the macro functionality in Jinja. It requires some workarounds/hacks because we cannot reach all the data from inside the django template system that we need, but it seems to work pretty well so far. It is, however, also pretty untested at this point, so use at your own risk. Examples: base.html: <!-- This is mandatory if you want to use the repeat-tag in a template. It should as placed as earily as possible. See below for how to mix with template inheritance. --> {% enablemacros %} <!-- Note that {{ param }} does not exist. --> {% block foo %} A standard django block that will be written to the output. {% if param %}{{ param }}{% endif %} {% endblock %} {% macro bar %} Pretty much the same thing as a django block (can even be overridden via template inheritance), but it's content will NOT be rendered per default. Please note that it ends with ENDBLOCK! {% if param %}{{ param }}{% endif %} {% endblock %} <!-- Render foo for the second time --> {% repeat foo %} <!-- Render foo bar the first time --> {% repeat bar %} <!-- Render both blocks again, and pass a parameter --> {% repeat foo with "Hello World" as param %} {% repeat bar with "Hello World" as param %} {% macro form %}do stuff with: {{ form }}{% endblock %} {% for form in all_forms %} {% repeat display %} <!-- will have access to {{ form }} {% endfor %} extend.html: <!-- {% extends %} requires that it be the first thing in a template, and if it is, everything except for block tags is ignored, so {% enablemacros %} won't work. Instead, use: --> {% extends_with_macros 'base.html' %} {% block foo %} Will override "foo" in base.html {% endblock %} {% block bar %} Will override the macro block "bar" in base.html. Whether this is defined as block or macro doesn't matter. {% endblock %} Todo: * This (both tags used) results in infinite recursion: {% extends_with_macros "somefile" %}{% enablemacros %}

  • templates
  • macro
  • jinja
  • repeat
  • reuse
  • variables
Read More

script for run a django task

when running a console script to access django or your models, you need to setup django environment properly and that is very annoying if you have quite a few scripts. this script can be used as a wrapper just like the manage.py. put it in your project root and type this: python run.py myproj.appname.filename.functionname [arguments] and define your function as def functionname(argv[]): ...

  • task
  • console
  • script
Read More

Tablify templatetag

`{% tablify questions name response 8 %}` Will generate a table structure of a list, ensuring that a set number of columns is not exceeded. It takes 4 arguments: *Context Variable *Cell Header Attribute *Cell Data Attribute *Max Number of Columns The code will loop through the given variable, creating th and td elements for each item. It will create a new tr when the max number of columns is exceeded.

  • templatetag
  • table
Read More

Name Capitalize Filter

This is to be used as a template filter. See [django documentation](http://www.djangoproject.com/documentation/templates_python/#writing-custom-template-filters) for adding custom filters. Example of use: name = "bart simpson" `{{ name|cap }}` will convert 'name' to "Bart Simpson" It works on space-separated names, as well as the following: * converts "mcfly" to "McFly"; * converts "o'neill" to "O'Neill"; * converts "barker-bradley" to "Barker-Bradley"

  • names
  • template-filters
  • capitalize
Read More

Handy tag for generating URLs to media files

Returns an absolute URL pointing to the given media file. The first argument is the path to the file starting from MEDIA_ROOT. If the file doesn't exist, empty string '' is returned. For example if you have the following in your settings: MEDIA_URL = 'http://media.example.com' then in your template you can get the URL for css/mystyle.css like this: {% media 'css/mystyle.css' %} This URL will be returned: http://media.example.com/css/style.css.

  • template
  • tag
  • media
Read More

roman numbers template filter

dirt and simple template filter to convert a number to its roman value. taken from dive into python http://www.diveintopython.org/unit_testing/stage_5.html

  • template
  • filter
  • filters
  • roman
  • numbers
Read More

media_url context variable

with this you can have context variables which know the media url and the urls of all your applications, if you need it. save the code as myapp/context_processors.py and add the following line to `TEMPLATE_CONTEXT_PROCESSORS` setting "mysite.myapp.context_processors.url_info", For each application you need to know the url set `MYAPP_URL` and add it to dict.

  • url
  • media
  • context
Read More

Avoid IE Brokenness When using Vary and Attachments

Apparently Internet Explorer (6 and 7) have a bug whereby if you blindly attach a PDF or some other file, it will choke. The problem lies in the Vary header (bug described in http://support.microsoft.com/kb/824847/en-us?spid=8722&sid=global). To use, just add to the beginning of your middleware classes.

  • middleware
  • ie
  • vary
Read More

Search results pagination

**Problem**: You search by firing POST and paginate by firing GET, so search results disappear on GET. I want to preserve searching results, so user can paginate them. First I try to use some static class to keep search results, but this solution has bug (thanks to svetlyak). In multiuser environment other user searching got results from previous one. No @cache_control(private=True) helps so I decided to change searching schema by using GET in the first place and to supply query string on each 'paging' request. Also added some memory cache that expires after 5 min **In template** Please append query to each paging link: <a href="?page={{ page_number }} &amp;search_query={{ query|urlencode }}"> {{ page_number }}</a> This snippet should keep search results on pagination in multiuser environment.

  • search
  • pagination
  • static-class
Read More

WordWrap template tag

Basically a clone of the default "wrap" filter. I use it to generate plaintext e-mail that has to be broken at 75 characters. {% wordwrap 80 %} Some text here, including other template tags, includes, etc. {% endwordwrap %} I prefer this over the {% filter wordwrap:80 %} as my template (e-mail) writers keep screwing it up.

  • template
  • tags
  • wordwrap
Read More

IfValueTag

Don't repeat yourself: when you wish to have a block of html with a variable value, but only if the variable is set, you can do this: {% ifvalue company.contact.email as email %} <h3>Email address</h3> <a href='mailto:{{ email }}'>{{ email }}</a> {% endifvalue %} Instead of this: {% if company.contact.email %} <h3>Email address</h3> <a href='mailto:{{ company.contact.email }}'>{{ company.contact.email }}</a> {% endifvalue %} The tags ifvalue and ifnotvalue are provided by this snippet. If you don't specify `as somename`, then the variable's value will be assigned to the name "value".

  • tag
Read More

Modelaware json serializer

A serializer that handles dicts with querysets and model instances, nice to use if you have a paginator context. paginate_by = 8 paginator = ObjectPaginator(queryset, paginate_by) page = request.GET.get('page', 1) try: page = int(page) object_list = paginator.get_page(page - 1) except (InvalidPage, ValueError): if page == 1 and allow_empty: object_list = [] else: raise Http404 result = { 'object_list' : object_list, 'is_paginated': paginator.pages > 1, 'results_per_page': paginate_by, 'has_next': paginator.has_next_page(page - 1), 'has_previous': paginator.has_previous_page(page - 1), 'page': page, 'next': page + 1, 'previous': page - 1, 'pages': paginator.pages, 'hits' : paginator.hits, } serialize(result, ensure_ascii=False)

  • json
  • serialization
Read More

3110 snippets posted so far.