Login

Top-rated snippets

Snippet List

several_random template filter

Allows the selection of one or more items from a list. The built-int `random` filter only allows you to select a single at a time, and repeated use can return the same item many times. **Example:** `{% for random_item in item_list|several_random:3 %} ... {% endfor%}` **Note:** If you're running this on an uncached QuerySet, it can result in many database queries... a future improvement might check to see if the passed object is a QuerySet and act accordingly.

  • filter
Read More

a template tag to invoke a method on an object with a variable

The django templating language is quite nice, and specifically limited to guide people in to making their business logic in the view, not in the template itself. Sometimes it can be difficult to do certain things in the template even though it seems like the most appropriate place to do this. I have an application that is heavily influenced by the user that is logged in in several ways. For example let us say I have a list of forums. Each forum has several discussions full of posts. This system of forums and discussions has permissions such that some users can not see some entities. Now, I can produce in the view the query set of what forums a user is allowed to see, and I want this list to display the latest post in each of those forums, but I have to restrict that to the posts that they can see. Easy enough, I have a method on the Forum object that takes a user object and does the appropriate filter to return the latest post that the user can see. The trick is the template is passed the query set of forums, and then iterates through them using the template language. How can it invoke the method on the forum for the latest post that needs the 'user' variable from the template context? The template language lets me say 'forum.latest_post' but I need to pass in 'user'. 'forum.latest_post(user)' does not work because the template language does not allow it. This tag lets me specify an object, the method on that object to call, and the variable to pass to that method. It is not the prettiest thing but with this add on you can do: `{% method_arg forum latest_post user as post %}`

  • tags
Read More

SmartyPants Filter

Really simple filter for using Smartpants in your template -- placed in your custom filters file. Requires python smartypants to be installed.

  • filter
  • typography
  • smartypants
Read More

Roman Numeral Filter

Template filter to convert integer or long integer into roman numeral with support for upper and lower case numerals. Requires python-roman package on Debian which apparently comes from http://www.diveintopython.org/

  • django
  • python
  • roman-numerals
Read More

render_markup filter, specify the markup filter as a string

Ever since django.contrib.markup appeared I've added a `markup_lang` field to my models where I want to support multiple input formats. This filter lets you pass the filter name as a string (from your model field, for example) and it will call the appropriate filter. I use None when the text is HTML, in which case it will return as-is. Example: class Article(models.Model): content = models.TextField(null=False, default="") markup_lang = models.CharField(maxlength=20, blank=True) a = Article(content="**Test!**", markup_lang='textile') b = Article(content="<h1>Hello!</h1>") And in a template: {% for article in article_list %} {{ article.content|render_markup:article.markup_lang }} {% endfor %}

  • filter
  • markup
Read More

FieldsetForm

This is FieldsetForm for rendering forms with fieldsets. This is not in anyway final version of this snippet. This is preliminary version which just works. One can easilly implement the `as_ul`, `as_p` at the end with just looking the `as_table` definition. > Content developers should group information where natural and appropriate. When form controls can be grouped into logical units, use the FIELDSET element and label those units with the LEGEND element... - [Web Content Accessibility Guidelines 1.0](http://www.w3.org/TR/WCAG10-HTML-TECHS/#forms-grouping) **Notice**: Since this uses *real* fieldset elements of HTML we had to define `form.as_table` the way it *includes* the `table` element around it. **Usage in template** {{ form }} and **not** `<table>{{ form }}</table>` **Usage in view** Following usage example is for *django.contrib.flatpage*, but naturally you can use it to whatever you want. Example assumes user knows about newforms and basics to how to use `form_for_*` functions from THIS-SNIPPETS-POSITION-IN-PYTHON-PATH import form_fieldsets ... fieldsets = form_fieldsets( (None, {'fields': ('url','title','content',)} ), ("Advanced options", {'fields': ('sites', 'template_name', 'registration_required',), 'classes':'collapse'}) ) ... ... forms.models.form_for_instance(flatpage, **fieldsets) ... forms.models.form_for_model(FlatPage, **fieldsets) ... Above creates two fieldsets: 1. "None" named fieldset (meaning no name is given) with fields 'url', 'title' and 'content'. 2. "Advanced options" named fieldset with fields 'sites', 'template_name' and 'registration_required' and collapse class in place. Syntax of form_fieldsets function is identical with models `class Admin: fields = (...)`, actually you can use admins exact line here with adding it like `form_fieldsets(*FlatPage.Admin.fields)` if you prefer that, although it wrecks the point of having newforms admin, if one does identical forms as in admin part. Purpose of this is not to create identical forms as in admin but to provide easy fieldsets for all views and forms. To follow DRY principle this should be part of Django and Django's newforms-admin branch should start to use some subclassing of this. But even if the newforms-admin branch never take this in, it is more DRY than without to use this in own projects, with this in place you can forget all template hazzles defining fieldset manually. **Some "counter" statemets for having this** > **S**: "But I want to define the table tag myself in template!" **A**: Well, you understod something wrong; First of all, for example, if there is something missing from the output of this table tag, you can feel free and subclass from FieldsetForm and define own as_table. Second of all, for having own table tag there can be only one reason to that, you want extra arguments, and that is TODO, but it is also easy piece. I haven't just needed extra stuff yet so they are not implemented. > **S**: "But, oh my! (newforms) admin does this already!" **A**: For the **last time** this is not meant for only newforms admin, you can use this on **any** given view or form renderition, since currently django does not give a simple way to use that handy fieldset automation in own views. And currently (9th of April, 2007) newforms admin does not do it this way. > **S**: "But, I want to use as_p, as_ul ..." **A**: Go ahead and fix them below... Should be pretty easy stuff. > **S**: "Each model should have only one fieldsets setting." **A**: I don't believe that; even if I did that is not convincing, since there are views that are not based on models, just bunch of fields, how would you define their fieldsets if it is not defined in the form renderition at the first place? This is the right place to define fieldsets. And the point of *FieldsetForm* is not just having multiple fieldsets per model, it is about *where* and *how* to render them.

  • newforms
  • admin
  • fieldset
Read More

Password Reset Form Newforms

A Change Password form that asks the user for the old password and checks the two new passwords. Whenever you instantiate the form you must pass a User object to it. ex. theform = forms.PasswordReset(request.user,request.POST)

  • newforms
  • password-reset
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

Better render_to_response

I'm finding this much more efficient (from a coding perspective) than using the `render_to_response` shortcut. It looks complex, but it's simple to use: just look at the example in the docstring. Call this script `renderer.py` and chuck it in your project root.

  • render_to_response
  • decorator
Read More

truncate letters

filter for truncating strings similar to truncatewords only with letters.

  • filter
  • truncate
  • letters
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

Win32 Read Registry Tag

Sometimes you need to grab information from the registry. This will only work if you have admin rights on the box you're querying.

  • win32
  • registry
Read More
Author: mpa
  • 1
  • 0

Setting distinction between development and public server

If your code is under source control and you develop locally and then publish that globally, you might need to modify the settings file after each update to ensure the system paths and database settings are correct. This simple solution helps to distinguish development server from the public server. And you won't need to care about modifying files on the public server anymore. Create a file called `dev_environment.py` in your `site-packages` directory of the development server only (do not put it under source control). Then use the following lines in the beginning of your files, you want to check whether you are in the development environment. try: from dev_environment import * except: is_dev_environment = False Then for example, you can set the database settings according the environment: if is_dev_environment: DATABASE_NAME = "test" DATABASE_USER = "root" DATABASE_PASSWORD = "" else: DATABASE_NAME = "publicproject" DATABASE_USER = "projectuser" DATABASE_PASSWORD = "ahl3379ljkasd"

  • development
  • public
Read More

3110 snippets posted so far.