Login

3110 snippets

Snippet List

Clear nullable foreign keys on delete

Django 1.0 is apparently hard-coded for cascading deletes. I find that I often have nullable foreign keys on models whose records must not be deleted along with those they refer to. I override Model.delete() in an intermediate base class and execute this method to clear out all nullable foreign keys before allowing a delete to proceed.

  • model
  • delete
  • cascade
Read More

path.py FilePathField

A slightly adapted FilePathField that converts path.py (http://pypi.python.org/pypi/path.py) objects into strings and back from the database.

  • custom field
  • filepathfield
  • path.py
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

Add site info to request context

Sometimes you want to generate a **really** absolute URL, but the built-in url tag only generates a URL relative to the current domain. This context processor adds the extra information needed to the request context, so you can generate an absolute URL in a template like so: `{{ protocol }}://{{ domain }}{% url someview %}` This is similar to how the password reset email from contrib.auth generates the full URL in the email. Save this somewhere as context_processors.py (or add to existing file if you have one), and add context_processors.site to your TEMPLATE_CONTEXT_PROCESSORS setting.

  • contextprocessor
  • domain
  • site
Read More

Model dependency graph using graphviz (script)

Instructions: Set your environment variables, install graphviz, and run. Finds all models in your installed apps and makes a handsome graph of your their dependencies based on foreignkey relationships. Django models have green outlines, yours have purple. The edge styling could be changed based on edge type.

  • models
  • graph
  • graphviz
Read More

Paginator TemplateTag

**Paginator TemplateTag** TemplateTag to use the new Paginator class directly from a template. The paginate template tags take the following options: 1. list or queryset to paginate 2. number of pages 3. [optionaly] name of the Paginator.Page instance; prefixed by keyword 'as' 4. [optionaly] name of the http parameter used for paging; prefixed by keyword 'using' If you want to specify the parameter name with the keyword 'using' you must use the 'as' keyword as well. The default name of the paging variable is "page" and the paginator (the class that knows about all the pages is set in the context as "page_set". This follows the naming scheme of the ORM mapper for relational objects where "_set" is appended behind the variable name. Usage, put the following in your template: {% load paginate %} {% get_blog_posts blog_category as posts %} {% paginate posts 10 as page using page %} <ul> {% for post in page.object_list %} <li>{{ post.title }}</li> {% endfor %} </ul> <div> {% if page.has_previous %} <a href="?page={{ page.previous_page_number }}">previous</a> {% endif %} <i>{{ page.number }} of {{ page_set.num_pages }}</i> {% if page.has_next %} <a href="?page={{ page.next_page_number }}">next</a> {% endif %} </div> The templatetag requires the request object to be present in the template context. This means that you need 'django.core.context_processors.request' added to settings.TEMPLATE_CONTEXT_PROCESSORS list or otherwise make sure that the templatetag can access the request object. Comments are appreciated.

  • templatetag
  • pagination
  • paginator
Read More

Class-Based AJAX fallback view

If you're used to auto_render like I am (and think it's an awesome way to DRY code) and you want to support users with and without javascript enabled, this class is perfect. You will need to provide the format requested, either through adding "(\.format)?" at the end of the url or through some middleware, but once you've done so this class will take care of rendering through the given template for normal users, JSON or JSONP for AJAX users. From [fahhem.com](http://fahhem.com/) and [Recrec Labs](http://recreclabs.com/)

  • ajax
  • view
  • json
  • class
  • fallback
  • class-based
Read More

Template Tag for Retrieving complex Settings

Very much like the snippet joshua wrote (http://djangosnippets.org/snippets/67/) for the same purpose but with the addition that this lets the user get values for more complex settings like dicts and lists

  • settings
  • template tag
Read More

Django-admin autoregister -- automatic model registration

Automatically register models for the Django-admin. This snippet aids in the process of keeping your admin.py up-to-date with the models in your apps, have all models automatically added to the admin and reflect any future changes without updating the file. [zweckdev.com](http://zweckdev.com/)

  • django
  • models
  • admin
  • model
  • django-admin
  • autoregister
  • auto-register
Read More

MultipleChoiceCommaField

MultipleChoiceCommaField - CheckboxSelectMultiple value sequence as a single string, comma-separated. Since I frequently want to store multiple-selected choice items as a single field in the model, I found it convenient to write a custom field class. The code uses the comma as a separator, but it could be easily generalized to use any delimiter.

  • newforms
  • checkbox
  • multiple
  • choice
  • selection
Read More

Delete View

Usage: @login_required def action_delete(request,object_id): return delete_view(request,object_id,ActionItem)

  • view
  • delete
Read More