Login

Top-rated snippets

Snippet List

Include entire networks in INTERNAL_IPS setting

A simple addition to the settings.py file of your project to allow you to easily specify entire network ranges as internal. This is especially useful in conjunction with other tools such as the [Django Debug Toolbar](http://github.com/robhudson/django-debug-toolbar/tree/master). After you set this up, the following test should pass test_str = """ >>> '192.168.1.5' in INTERNAL_IPS True >>> '192.168.3.5' in INTERNAL_IPS FALSE """ Requirements ------------ * The [IPy module](http://software.inl.fr/trac/wiki/IPy) Acknowledgements ---------------- Jeremy Dunck: The initial code for this idea is by Jeremy and in [Django ticket #3237](http://code.djangoproject.com/ticket/3237). I just changed the module and altered the use of the list superclass slightly. I mainly wanted to put the code here for safe keeping. Thanks Jeremy!

  • settings
  • ip-addresses
  • cidr
  • internal-ips
Read More

Fuzzy Date Diff Template Filter

Pass in a date and you get a humanized fuzzy date diff; e.g. "2 weeks ago" or "in 5 months". The date you pass in can be in the past or future (or even the present, for that matter). The result is rounded, so a date 45 days ago will be "2 months ago", and a date 400 days from now will be "in 1 year". Usage: * `{{ my_date|date_diff }}` will give you a date_diff between `my_date` and `datetime.date.today()` * `{{ my_date|date_diff:another_date }}` will give you a date_diff between `my_date` and `another_date` Make sure to install this as a template tag and call `{% load date_diff %}` in your template; see the [custom template tag docs](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/) if you don't know how to do that.

  • template
  • filter
  • date
  • humanize
Read More

Saving passwords for other services (semi-)securely in a database

I've often found myself wanting to store passwords for other web services (e.g. maillist managers, IMAP accounts, IM accounts etc) for use by a web application, but have not wanted to hard-code them in `settings.py` or store them as plaintext in the database. This uses the [pycrypto][] library to encrypt each bit of information using the concatenation of a salt value and the SECRET_KEY value from your `settings.py`, hopefully leading to a bit more security and flexibility. [pycrypto]:http://www.dlitz.net/software/pycrypto/ You'll probably want to add some views to let people edit these things as I can't find a way to make the admin interface play nicely with it. **Example usage:** In [1]: p = Password( name='IMAP account', slug='imap', username='example', password='password', host='imap.gmail.com' ) In [2]: p.host Out[2]: 'imap.gmail.com' In [3]: p.e_host Out[3]: '6wdyMDKYy8c=$YXw6t/Q9wI[...]' In [4]: p.save()

  • password
  • crypto
Read More

BetterForm with fieldsets and row_attrs

**NOTE**: Further development of this snippet will take place in the [django-form-utils](http://launchpad.net/django-form-utils) project. This snippet provides BetterForm and BetterModelForm classes which are subclasses of django.forms.Form and django.forms.ModelForm, respectively. BetterForm and BetterModelForm allow subdivision of forms into fieldsets which are iterable from a template, and also allow definition of row_attrs which can be accessed from the template to apply attributes to the surrounding container of a specific form field. It's frequently said that a generic form layout template is a pipe dream and in "real usage" it's necessary to manually layout forms, but in my experience the addition of fieldsets and row_attrs, plus a competent CSS designer, make it possible to create a generic template that can render useful production form markup in 95+% of cases. Usage: class MyForm(BetterForm): one = forms.CharField() two = forms.CharField() three = forms.CharField() class Meta: fieldsets = (('main', {'fields': ('two',), 'legend': ''}), ('Advanced', {'fields': ('three', 'one'), 'description': 'advanced stuff'})) row_attrs = {'one': {'style': 'display: none'}} Then in the template: {% if form.non_field_errors %}{{ form.non_field_errors }}{% endif %} {% for fieldset in form.fieldsets %} <fieldset class="fieldset_{{ fieldset.name }}"> {% if fieldset.legend %} <legend>{{ fieldset.legend }}</legend> {% endif %} {% if fieldset.description %} <p class="description">{{ fieldset.description }}</p> {% endif %} <ul> {% for field in fieldset %} {% if field.is_hidden %} {{ field }} {% else %} <li{{ field.row_attrs }}> {{ field.errors }} {{ field.label_tag }} {{ field }} </li> {% endif %} {% endfor %} </ul> </fieldset> {% endfor %}

  • fieldset
  • form
  • layout
Read More

"Partial Templates" - an alternative to "include"

This snippet adds simple partial support to your templates. You can pass data to the partial, and use it as you would in a regular template. It is different from Django's `{% include %}`, because it allows you to pass a custom variable (context), instead of reusing the same context for the included template. This decouples the templates from each other and allows for their greater reuse. The attached code needs to go into `templatetags` folder underneath your project. The usage is pretty simple - `{% load ... %}` the tag library, and use `{% partial_template template-name data %}` in your template. This will result in template passed as **template-name** to be loaded from **partials** folder. The **.html** extension will be appended to the file name. The file has to be in one of template paths accessible to the loader) and rendered with **data** as its context. The data is available in the template as an `item` context variable. You can find more information in the [relevant Django documentation](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags)

  • template
  • tag
  • templates
  • tags
  • partial
  • include
  • partials
Read More

ManyToManyField no syncdb

**Sumary** M2M relation without creating table. Normally you should specify m2m only in *one* model, thus widgets for many-to-many relations will be displayed inline on whichever model contains the actual reference to the ManyToManyField. But if you want to be able to have widgets displayed on both form you need some tricks, for example using intermediary-models can help, but you will not get multiselect widget (and in case of inlining extra = multi). Also you can write your own form which takes care about adding widget (just 1 line) and setting default values and saving it (more than few lines of code). If you try ManyToManyField with same db_table specified, the only problem will be in syncdb (it will try to create two identical tables) and the only thing our class does is preventing creation of table for M2M, so in one model you should use ManyToManyField and in another ManyToManyField_NoSyncdb with the same db_table argument. **Example** So to have M2M widgets in both forms you can write: class User(models.Model): #... groups = ManyToManyField('Group', related_name='groups', db_table=u'USERS_TO_GROUPS') class Group(models.Model): #... users = ManyToManyField_NoSyncdb(User, related_name='users', db_table=u'USERS_TO_GROUPS')

  • model
  • field
  • manytomany
  • manytomanyfield
  • syncdb
Read More

Unobtrusive comment moderation, updated for Django 1.0

This is the "unobtrusive comments moderation" code from http://www.djangosnippets.org/snippets/112/ , but updated so it works properly with Django 1.0. There are only a few small changes reflecting changes in the comments, contenttypes, and signals APIs. For full background, see the original snippet: http://www.djangosnippets.org/snippets/112/

  • akismet
  • comments
  • moderation
Read More

SelectTimeWidget

This snippet defines a Widget that is very similar to the **SelectDateWidget** located in django.forms.extras.widgets. The main difference however is that it works with Times instead of Dates. The SelectTimeWidget supports both 24-hr and 12-hr formats, and flexible time increments for hours, minutes and seconds. Sample usage is illustrated below: # Specify a basic 24-hr time Widget (the default) t = forms.TimeField(widget=SelectTimeWidget()) # Force minutes and seconds to be displayed in increments of 10 t = forms.TimeField(widget=SelectTimeWidget(minute_step=10, second_step=10)) # Use a 12-hr time format, which will display a 4th select # element containing a.m. and p.m. options) t = forms.TimeField(widget=SelectTimeWidget(twelve_hr=True))

  • forms
  • widgets
Read More

template tag for highlighting currently active page

This module defines a template tag `{% ifactive %}` that lets you determine which page is currently active. A common use case is for highlighting the current page in a navigation menu. It uses the same syntax for specifying views as the `{% url %}` tag, and determines whether a particular page is active by checking if the same view is called with the same arguments, instead of just comparing URLs. As a result, it can handle cases where different URLs map to the same view. Example usage: <a {% ifactive request page1 %}class='active'{% endifactive %} href='{% url page1 %}'>Page 1</a> <a {% ifactive request page2 %}class='active'{% endifactive %} href='{% url page2 %}'>Page 2</a> ... <a {% ifactive request pageN %}class='active'{% endifactive %} href='{% url pageN %}'>Page N</a> It also can be extended to further reduce the amount of repetitive code. For instance, you could write a template tag that has class='active' as the block contents, and always gets the variable from context['request']: def do_activeif(parser, token): "e.g. <a {% activeif page1 %} href='{% url page1 %}'>Page 1</a>" tag_args = token.contents.split(' ') view_name = tag_args[1] args, kwargs = _parse_url_args(parser, tag_args[2:]) return ActiveNode('request', view_name, args, kwargs, NodeList(TextNode('class="active"'))) register.tag('activeif', do_activeif) Note that you will have to add the ActiveViewMiddleware to your settings.py: MIDDLEWARE_CLASSES = ( ..., 'path.to.this.module.ActiveViewMiddleware' ) You may also want to add this template tag as a built-in, so you don't have to call `{% load %}`. In somewhere that's imported by default (e.g. where you define your views), add: from django import template template.add_to_builtins('path.to.this.module')

  • template
  • tag
  • page
  • active
  • ifactive
Read More

FieldAccessForm (per-field user access for forms derived from models)

=== version 2 === > Parts of this code are based off of source from *davidcramer* on #django and I'd like to thank him for his assistance. Example: # forms.py ... class ForumPostForm(FieldAccessForm): class Meta: model = ForumPost class FieldAccess: moderator = FieldAccessLevel( lambda user, instance: user.get_profile().is_moderator, enable = ('approve', 'delete', 'edit') member = FieldAccessLevel( lambda user, instance: user.is_active, enable = ('edit',), exclude = ('approve', 'delete') ... # template ... <form action="" method="POST"> <table> {% for field in form %} <tr><th>{{ field.label_tag }}</th><td> {% if not field.field.disabled %} {{ field }} {% else %} {{ field.field.value }} {% endif %} </td></tr> {% endfor %} </table> <p><input type="submit" value="Update" /></p> </form> ... This class will grant or deny access to individual fields according to simple rules. The first argument must be a user object, but otherwise, this class is instantiated the same as a ModelForm. To utilize this code, inherit your form from FieldAccessForm, and create an inner class on your form called FieldAccess. Variables added to this inner class must have the same structure as that provided by the FieldAccessLevel class, which defines an access level, and the fields which apply to that access level. FieldAccessLevel takes as it's first argument a callable rule that validates this access level. That rule will be called with two arguments: 'user' (current user requesting access) and 'instance' (model instance in question). The keyword arguments to FieldAccessLevel are field groups which are used to determine which fields on this form are to be enabled and/or excluded, when the current user matches this access level. The term exclude indicates fields which are not to be rendered in the form at all. Any fields not grouped in either 'enable' or 'exclude' will be disabled by default. Superusers are always assumed to have full access. Otherwise, if a field is not specified with the FieldAccess inner class, then it is disabled by default. In other words, all users (except superusers) are denied access to all fields, unless they are specifically given access on a per-field basis. It is worth mentioning that multiple access levels can apply simultaneously, giving a user access to fields from all levels for which he matches the rule. If a user is denied access to a field, then the widget for that field is flagged as disabled and readonly. The field is also given two new attributes: a boolean 'disabled', and a 'value' containing the instanced model field. These two attributes allow a template author to have great control over the display of the form. For example, she may render the plain text value of a field instead of the disabled widget. The FieldAccess inner class also allows one to conditionally exclude fields from being rendered by the form. These exclusions operate very similarly to the standard Meta exclude option, except that they apply only to the access level in question. Note: The FieldAccess inner class may be used on both the form and the model; however, generally it makes more sense on the form. If you do use FieldAccess on both the form and model, be aware that both definitions will apply simultaneously. All access levels for which the user passes the rule will be processed, regardless of whether they were found on the form or the model.

  • form
  • field
  • permission
  • modelform
  • access
Read More

SizeAndTimeMiddleware

Used for showing size of the page in human readable format and time taken to generate the page on the server. To use it, in your base template, somewhere put the line: `<!-- ____SIZE_AND_DATE_PLACEHOLDER____ -->`. May be used on production.

  • middleware
Read More

django_stateful

this snippet provides a class that can be subclassed for creating views that retain state between requests, you can read more here http://code.google.com/p/django-stateful/ your comments are welcome!

  • django
  • stateful
  • seaside
  • continuations
Read More

Cachable Class Method Decorator

This decorator does automatic key generation and simplifies caching. Can be used with any class, not just model subclasses. Also see [Stales Cache Decorator](http://www.djangosnippets.org/snippets/1131/).

  • cache
  • decorator
Read More

Gravatar support for Django comments

A templatetag to add [Gravatar](http://www.gravatar.com/) support for [Django comments](http://docs.djangoproject.com/en/dev/ref/contrib/comments/ "Django Comments"). Based on [this snippet](http://www.djangosnippets.org/snippets/772/) but works for everyone who comments even if they are not a registered user.

  • comments
  • gravatar
Read More

3110 snippets posted so far.