Login

Most bookmarked snippets

Snippet List

Making a django inline (model) formset really tabular

As there is no straight way to re-produce the real tabular inline formsets you get in django-admin, here is how this template has to look like if you do it form your own formsets generated from formset factories.

  • template
  • form
  • modelform
  • formset
  • inline
Read More
Author: fnl
  • 5
  • 6

Page numbers with ... like in Digg

Digg-like page numbering using inclusion tag. Usage in template: {% load pagination %} {% pagination yourpage %} Inclusion template `pagination.html`: {% load i18n %} <div class="pagination"> <span class="step-links"> {% if page.has_previous %} <a href="?page={{ page.previous_page_number }}" class="previous">{% trans "previous" %}</a> {% endif %} {% for pnum in begin %} {% ifequal page.number pnum %} <span class="current">{{ pnum }}</span> {% else %} <a href="?page={{ pnum }}">{{ pnum }}</a> {% endifequal %} {% endfor %} {% if middle %} <span class="continue">...</span> {% for pnum in middle %} {% ifequal page.number pnum %} <span class="current">{{ pnum }}</span> {% else %} <a href="?page={{ pnum }}">{{ pnum }}</a> {% endifequal %} {% endfor %} {% endif %} {% if end %} <span class="continue">...</span> {% for pnum in end %} {% ifequal page.number pnum %} <span class="current">{{ pnum }}</span> {% else %} <a href="?page={{ pnum }}">{{ pnum }}</a> {% endifequal %} {% endfor %} {% endif %} {% if page.has_next %} <a href="?page={{ page.next_page_number }}" class="next">{% trans "next" %}</a> {% endif %} </span> </div> Produces: previous 1 2 ... 4 5 6 7 **8** 9 10 11 12 ... 17 18 next Or: **1** 2 3 4 5 6 7 8 ... 17 18 next Or: previous 1 2 ... 10 11 12 13 14 15 16 **17** 18 next

  • tag
  • django
  • templatetag
  • pagination
  • digg
  • pages
Read More

Readonly fields on Form/Modelform

A Form and ModelForm which provides the ability to specify certain fields as readonly, meaning that they will display their value as text wrapped with a <span> tag. The user is unable to edit them, and they are protected from POST data insertion attacks. The recommended usage is to place a NewMeta inner class on the form, with a readonly attribute which is a list or tuple of fields, similar to the fields and exclude attributes on the Meta inner class. class MyForm(ReadonlyForm): foo = forms.TextField() bar = forms.TextField() class NewMeta: readonly = ('foo',) Use these forms as you would a standard form in your templates.

  • forms
  • field
  • readonly
  • modelforms
  • span
Read More

Load customized SQL

A management.py loading customized SQL feeding it raw to the database backend. Just put it as `management.py` in your app and put whatever SQL you want run after syncdb in `app/sql/custom.backend_driver.sql`. If the `backend_driver` is skipped the SQL will be loaded no matter database backend. Since it is run after syncdb it will also be run for test.

  • sql
  • test
  • "initial
Read More

BeforeFilter Middleware

Expanded version of [snippet 715](http://www.djangosnippets.org/snippets/715/ "Django snippets: Simple View Middleware to allow a Prefilter") to be more flexible. Updates: * 2009-04-24: Multiple filters now work correctly * 2009-03-22: Fixed bug * 2009-02-03: Simplified process.

  • middleware
  • process_view
  • beforefilter
Read More

AddThis Social Networking TemplateTag

Code to add an 'AddThis' button to your blog posts. Simply do: {% add_this post.title post.get_absolute_url %} Also, specify your ADD_THIS_USERNAME to your settings. <!-- blog/add_this.html --> <script type="text/javascript">var addthis_pub="{{ username }}";</script> <a href="http://www.addthis.com/bookmark.php" onmouseover="return addthis_open(this, '', '{{ site.domain }}{{ url }}', '{{ site.name }} - {{ title }}')" onmouseout="addthis_close()" onclick="return addthis_sendto()"> <img src="http://s7.addthis.com/static/btn/lg-addthis-en.gif" width="125" height="16" border="0" alt="" style="border:0"/></a> <script type="text/javascript" src="http://s7.addthis.com/js/152/addthis_widget.js"></script>

  • template-tag
  • add-this
  • social-networking
Read More

ModelForm ExtJS JSON Encoder

from http://www.djangosnippets.org/snippets/792/ from utils.extjs import ExtJSONEncoder from django.utils.safestring import mark_safe class TestForm(forms.ModelForm): class Meta: model = TestModel def as_ext(self): return mark_safe(simplejson.dumps(self,cls=ExtJSONEncoder))

  • json
  • modelform
  • extjs
Read More

Truncate string after a given number of chars keeping whole words

Truncates a string after a given length, keeping the last word complete. This filter is more precise than the default `truncatewords` filter. Words length vary too much, 10 words may result in 40 or 70 characters, so cutting by character count makes more sense. There is a [blog post](http://ricobl.wordpress.com/2008/12/23/templates-django-filtro-truncatewords-melhorado/) about this snippet (in Portuguese).

  • template
  • filter
  • templatetag
  • truncate
  • templatetags
  • words
Read More
Author: rix
  • 5
  • 6

Admin Input Field Character Count via jQuery

Use this code in *change_form.html* in your projects admin templates to add a character counter beside the input field(s) in admin to let users know how many characters they have remaining for a particular input field. The total number of characters allowed is determined by the max_length in your model for the models.CharField you're using this with. This code is designed to add the counter after the input field, but could easily be customized to fit the style of any admin. If the number of characters remaining is 10 or less the background color changes to yellow to visually warn the user. **Usage Examples:** In this example only the input field with id=id_pull_quote will receive the counter: $(document).ready(function() { $("#id_pull_quote").counter(); }); You could also apply the counter to all input fields on a page: $(document).ready(function() { $("form input[@maxlength]").counter(); }); **Note:** *You have to download jQuery to your project and place the appropriate call in order for this to work. The best place to do this is in the extrahead block. I left my call in as an example but your path and file name will probably vary.* Credit for base jQuery code goes to Brad Landis at [bradlis7.com](http://www.bradlis7.com).

  • template
  • javascript
  • admin
  • jquery
  • form
  • input
Read More

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

Model Forms: Clean unique field

Often I want fields in my models to be unique - Django's `unique` works too late in model form validation and will throw an exception unless you check for it by hand. This is a bit of code that cleans up the boiler plate of checking if different fields are unique. Set `exclude_initial` to `False` if you want to raise an error if the unique field cannot be set to whatever value the instance had before. **Update** Thanks fnl for rightly pointing out that Django's `unique=True` does check for this - just make sure to pass `instance=obj` when you're initializing your forms. _HOWEVER_ a problem you'll typically run into with this is though you want a field to unique, you also want multiple entries to be able to be `blank`. This can help you!

  • forms
  • model
  • unique
  • model-forms
Read More

Require Login Middleware

Wraps specified URL patterns with login_required decorator. Allows you to quickly require login for an area of your site based only on a URL pattern. Similar to [zbyte64's snippet](http://www.djangosnippets.org/snippets/966/)

  • middleware
  • authentication
  • url
  • login
  • auth
Read More

Pygments Syntax highlighting template tag

This template tag will attempt to apply pygments syntax highlighting to anything inside {% code %} and {% endcode %} tags. You can optionally pass in the language to highlight in the form of {% code 'lang' %} - if you don't, it will first try to guess the syntax, and then fall back to Python syntax highlighting.

  • templatetag
  • pygments
  • highlighting
  • syntax
Read More

UKPhoneNumberField

Validates and cleans UK telephone numbers. Number length is checked, and numbers are cleaned into a common format. For example, "+44 (0)1234 567890" will be stored as "01234 567890" Can reject premium numbers (09123 123123) or service numbers (1471, 118 118) with `UKPhoneNumberField(reject=('premium', 'service'))` Uses info from [Wikipedia](http://en.wikipedia.org/wiki/Telephone_numbers_in_the_United_Kingdom)

  • form
  • field
  • uk
  • localflavor
Read More

3110 snippets posted so far.