Login

All snippets written in JavaScript

Snippet List

Python-like string interpolation in Javascript

Provides python-like string interpolation. It supports value interpolation either by keys of a dictionary or by index of an array. Examples: interpolate("Hello %s.", ["World"]) == "Hello World." interpolate("Hello %(name)s.", {name: "World"}) == "Hello World." interpolate("Hello %%.", {name: "World"}) == "Hello %." This version doesn't do any type checks and doesn't provide formating support.

  • template
  • javascript
  • string interpolation
  • replace
Read More

Admin actions as buttons instead of a menu

Add this to any admin changelist and your actions drop-down will be replaced with user-friendly buttons. Why mess around with templates and subclassing admin classes when you can just mangle the page with jQuery! ;-) It also adds a 'select all' label to explain the mystery top check-box (well it was a mystery to several of my clients). The line "if ($('div.actions option:gt(0)').length<=8)" checks that there aren't more than 8 actions and falls back to the drop-down if there are. Requires jQuery to be loaded.

  • admin
  • actions
Read More

jstree integration to django admin

You have some tree-like structure in your models, for example: `class MyModel(models.Model): parent = models.ForeignKey('self', verbose_name=u'Parent', \ null=True, blank=True, related_name='children') name = models.CharField(u'Раздел', max_lengtch=255) position = PositiveSmallIntegerField(u'Позиция', default=0) class Meta: ordering = ('position',)` To see it as a tree in admin's object list(you also can sort items, move to another parents by drag-n-drop; and rename them) add this to admin.py: `class MyModelAdmin(admin.ModelAdmin): ordering = ('position',) list_display = ('pk','name','parent','position') raw_id_fields =('parent',) list_per_page = 900 #we sould have all objects on one page list_editable = ('name','position','parent') def parent_id(self,obj): return obj.parent and obj.parent.id or '0' class Meta: model = MyModel class Media: js = [settings.MEDIA_URL + s for s in ('lib/jquery-1.3.2.min.js', 'lib/jquery.tree.min.js', 'lib/plugins/jquery.tree.contextmenu.js', 'lib/mymodel_admin.js',)] css = { 'all':(settings.MEDIA_URL+'css/nestedsortablewidget.css',) }` mymodel_admin.js is the code listed here, if you have different title field(not "name"), change var title_column in javascript, list_display and list_editable. jstree can be obtained here: [jstree](http://www.jstree.com/) screenshot is in [my blog](http://tabed.org/blog/2010/01/06/jstree-in-django-admin/)

  • admin
  • model
  • tree
Read More

"Save and Continue" keyboard command for admin, with autoscroll

This snippet is helpful if you do a lot of editing on a single large admin form (for example, in a rich text field), and want to frequently save your progress. If you press control-S, or command-S on a Mac, the admin change form will save and reload, and the page will scroll back down to where you last were. This snippet relies on jquery, [jquery.cookie](http://plugins.jquery.com/project/cookie), and the [shortcut.js](http://www.openjs.com/scripts/events/keyboard_shortcuts/) keyboard library (which doesn't use jquery, but seemed more robust than the jquery keyboard plugins I saw). It uses a temporary cookie to remember where the page was scrolled to, to avoid having to override the admin behavior. Note: don't put this in templates/admin/change_form.html -- the circular import causes a Django crash. *Edit: Had forgotten to include jquery.cookie, which I was already including elsewhere.*

  • admin
  • jquery
  • save
Read More

Make hyperlinks for labels of raw_id_fields (jQuery)

The Django Admin site provides a "raw ID" feature for foreign keys that reference large tables. In the form view, the label of the referenced object will appear after the input. This snippet will make that label into a hyperlink that takes you to the form view for that object. To use this snippet, copy base_site.html into your templates/admin directory (if you haven't already), and paste this code into that file somewhere after the 'extends "admin/base.html"' directive. If you are already using jQuery, you can remove the first script tag. If you are already extending "extrahead", just paste the script tag(s) into the block you have created. [Documentation for raw_id_fields](http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.raw_id_fields)

  • admin
  • jquery
  • raw_id_fields
Read More

django-mptt enabled replacement for SelectBox.js

This snippet is used in conjunction with the code in [#1779](http://www.djangosnippets.org/snippets/1779/) to make an mptt-enabled version of the FilteredSelectMultiple widget. See my blog for full details: [http://anentropic.wordpress.com](http://anentropic.wordpress.com/2009/11/05/more-django-mptt-goodness-filteredselectmultiple-m2m-widget/)

  • widget
  • mptt
Read More

Confirm alert if the user navigates away without saving changes

A confirm alert is displayed if the user has made any changes to the form, and attempts to navigate away from the page without saving (click the back button, hit reload, click the breadcrumbs, logout, etc). Much like GMail's "Your message has not been sent. Discard your message?" prompt. **Uses the JavaScript helpers built into Django**, without relying on 3rd party libs like jQuery. (There might be simpler options if you're already using [jQuery](http://code.google.com/p/protect-data/) or [prototype](http://stackoverflow.com/questions/925111/activating-onbeforeunload-only-when-field-values-have-changed/1013033#1013033)). To use this, simply create a [custom admin template](http://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-admin-templates). For example at: *templates/admin/YOUR_APP_NAME/change_form.html* {% extends "admin/change_form.html" %} {% block after_related_objects %} {{ block.super}} <script type="text/javascript"> ... script goes here ... </script> {% endblock %}

  • admin
  • change-form
Read More

Dynamically add inlines

These functions use JQuery to dynamically add new entries for stacked or tabular inlines on a change form. To enable it, change the parent model to include this Javascript as well as JQuery. Here's an example: class MeetingAdmin(admin.ModelAdmin): inlines = [MeetingDonationInline, MeetingExtraInline] class Media: js = ["/media/jquery-1.3.2.min.js", "/media/dynamic_inlines.js"]

  • javascript
  • admin
  • jquery
  • inline
  • tabular
  • stacked
Read More

Collapsed stacked inlines

A simple jQuery javascript that collapses all stacked inline rows for better handling of large inline fieldsets. It also adds "Show"/"Hide"-buttons for showing/hiding each row, which could be customized and styled using css. **Usage (see below for example):** Include the javascript on your admin page, together with jQuery, and it'll automatically affect all stacked inlines. **Developed for:** * jQuery 1.3.2 * Django trunk (tested in Django v1.0.2) * (Might work with other versions with or without adjustments, but not tested) **Use example: ** *admin.py:* class DateInline(admin.StackedInline): model = Date extra = 10 class EventAdmin(admin.ModelAdmin): inlines = [DateInline] class Media: js = ['js/jquery-1.3.2.min.js', 'js/collapsed_stacked_inlines.js',] admin.site.register(Event, EventAdmin)

  • javascript
  • admin
  • jquery
  • inline
  • collapse
  • stacked
Read More

Dynamic tabular inlines with optional drag-n-drop sorting

This jQuery javascript enables dynamic add/delete of rows in tabular inlines. It adds a "+" icon at the bottom of the inline to allow addition of new rows, and replaces the default delete checkbox with a "x" icon for deletion, giving you the possibility to add/delete rows instantly without reloading the page. In addition, it gives you drag-n-drop ordering functionality with a named position model field using jQuery UI Sortable. **Usage (see below for example):** Just include the javascript on your admin page, together with jQuery, and it'll automatically affect all tabular inlines. Optionally, also include jQuery UI Sortable and an Integer field in your inline model named "position" (or whatever you set "position_field" to), which will automatically hide the position field and enable drag-n-drop sorting. **Developed for:** * jQuery 1.3.2 * jQuery UI 1.7.1 * Django trunk (tested in Django v1.0.2) * (Might work with other versions with or without adjustments, but not tested) **Settings (in top of javascript):** * "position_field" is the name of an integer model field that is used for ordering the inline model. If left empty or not found, the drag-n-drop functionality is dropped. Defaults to "position". * "add_link_html" for custom look of "add"-buttons. Defaults to Django's built-in "+" image icon. * "delete_link_html" for custom look of "delete"-buttons. Defaults to Django's built-in "x" image icon. **Use example: ** *admin.py:* class NameInline(admin.TabularInline): model = Name extra = 1 class PersonAdmin(admin.ModelAdmin): inlines = [NameInline] class Media: js = ['js/jquery-1.3.2.min.js', 'js/ui/ui.core.js', 'js/ui/ui.sortable.js', 'js/dynamic_inlines_with_sort.js',] css = { 'all' : ['css/dynamic_inlines_with_sort.css'], } admin.site.register(Person, PersonAdmin) *models.py:* class Person(models.Model): year_born = models.PositiveIntegerField(_('year born'), null=True, blank=True) class Name(models.Model): profile = models.ForeignKey(Profile, verbose_name=_('profile')) position = models.PositiveIntegerField(_('position'), default=0) name = models.CharField(_('name'), max_length=100) class Meta: ordering = ('position',) *dynamic_inlines_with_sort.css:* /* To make row height of saved items same as others */ .inline-group .tabular tr.has_original td { padding-top:0.5em; } .inline-group .tabular tr.has_original td.original p { display:none; } Please post bugs in comments.

  • javascript
  • dynamic
  • admin
  • sort
  • jquery
  • ordering
  • inlines
  • inline
  • tabular
  • sortable
Read More

jQuery slugify plugin

This plugin lets you make a field(ideally for a slug) populate itself based on the value of another field. You use it like this: jQuery('#id_title').slugify('#id_slug');

  • slug
  • jquery
  • slugify
Read More

Django Drag and Drop Using YUI

I was trying to implement the django inline drag & drop, I cudn't understand. Then I have try with YUI library Copy the above code in the respective .py & download the YUI library and add the JS in your media folder. This will do..., Try this our , it's easy to use..,

  • django
  • yui
  • drag
  • drop
  • and
Read More

Dynamically adding forms to a formset with jQuery

I recently worked on an application, where I had to provide a way for users to search for objects based on user-defined properties attached to these objects. I decided to model the search form using a formset, and I thought it'd be a good idea to allow users dynamically add and remove search criteria. The script (dynamic-formset.js) should be re-usable as-is: 1. Include it in your template (don't forget to include jquery.js first!). 2. Apply the 'dynamic-form' class to the container for each form instance (in this example, the 'tr'). 3. Handle the 'click' event for your `add` and `delete` buttons. Call the `addForm` and `deleteForm` functions respectively, passing each function a reference to the button raising the event, and the formset prefix. That's about it. In your view, you can instantiate the formset, and access your forms as usual.

  • newforms
  • jquery
  • dynamic-formset
Read More

60 snippets posted so far.