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
Originally based on: [http://djangosnippets.org/snippets/1872/](http://djangosnippets.org/snippets/1872/)
The way the original snippet formatted sql didn't work for mysql properly so I taught it to use the sqlparse python module. Now it looks like this when settings.DEBUG=True:
SQL executed:
SELECT "django_session"."session_key",
"django_session"."session_data",
"django_session"."expire_date"
FROM "django_session"
WHERE ("django_session"."session_key" = d326108d313a2e5c5fb417364b005ab9
AND "django_session"."expire_date" > 2011-04-08 14:54:13.969881)
took 0.001 seconds
SELECT "auth_user"."id",
"auth_user"."username",
"auth_user"."first_name",
"auth_user"."last_name",
"auth_user"."email",
"auth_user"."password",
"auth_user"."is_staff",
"auth_user"."is_active",
"auth_user"."is_superuser",
"auth_user"."last_login",
"auth_user"."date_joined"
FROM "auth_user"
WHERE "auth_user"."id" = 2
took 0.000 seconds
Additionally, this middlware is enabled conditionally based upon the url query string "debug". You can enable it for a single request by appending: ?debug=true to the url.
- middleware
- development
- debug