Login

3110 snippets

Snippet List

Simple Plone Migration

This is a very simple script to do a **simple** migration from plone content to django. ATNewsItems and PloneArticles are imported into the django model *Article* (with Foreignkey to the django models *File* and *Image*). ATDocuments are imported into the django model *Page*. **Usage** 1. Make sure that the Python version running Zope can import django 2. The django database should be writeable from within the Zope environment 3. Set the shell variable *DJANGO_MODULE_SETTING* to the settings file of the django project you want to import your Plone content to 4. Start the Zope server in the debug modus: $ bin/zopectl debug Then import the python module above, and pass the site you want to migrate to the start function: import simple_migration mysite = app.mysite simple_migration.start(mysite) Found 1253 objects Saved Test Document Type: ATNewsItem ... Hope it helps someone. Used for the migration of **Plone-2.5.3** content in a **Python-2.4.4** environment.

  • migration
  • import
  • plone
Read More

SQLLoggerMidleware + infobar

This middleware will add a log of the SQL queries executed at the top of every page, in the form of an IE-like 'infobar'. It also includes a query count and total and per-query execution times. This snippet is based on snippet #344 "SQL Log Middleware + duplicates" by guettli. I did some adjustments to the code, to also add support for the application/xhtml+xml mime type, aswell as add the code for the infobar. Need DEBUG on, aswell as DEBUG_SQL, should not be used on production sites. It also expects a 16x16 png image called infobar_icon.png, which it is looking for in the /media/images folder (or /static/images, depending on your MEDIA_URL setting). I used a little light bulb icon from the Tango icon set, but am unable to attach the image. Any 16x16 png will do off course. Update 0.1.1: In the initial version of this middleware, the path to /media/images was hard-coded, and you had to adjust this middleware accordingly. Now, it correctly uses the MEDIA_URL setting from your settings.py file, so you no longer have to edit this middleware. 0.1.2: Made some adjustments to the CSS to get rid of a padding bug when the bar was displayed on a Django error page. Also if a page contains no queries, it won't bother printing an 'empty' table, with just column headers. 0.1.3: More tweaks to the CSS, odd/even row shading on queries table. 0.1.4: More CSS tweaks again 0.1.5: Minor tweaks 0.1.6: Sorry, I just realised that after some time, this snippet broke in the latest SVN of Django with a Unicode error, as arthur78 mentioned. I have managed to fix it, by wrapping line 258 and 259 in an str() function.

  • sql
  • middleware
  • logger
Read More

Auto rendering decorator with options

This view decorator renders automaticaly the template with the context provided both by the view "return" statement. For example: @auto_render def my_view(request): ... return 'base.html', locals() You can still return HttpResponse and HttpResponseRedirect objects without any problems. If you use Ajax requests, this decorator is even more useful. Imagine this layout: def aggregating_view(request): ... context = locals() partial1 = partial_view_1(request, only_context=True) partial2 = partial_view_2(request, only_context=True) # aggregate template include partial templates return 'aggregate.htmt', context.update(partial1).update(partial2) def partial_view_1(request): ... return 'partial_1.html', locals() def partial_view_2(request): ... return 'partial_2.html', locals() This way you can render you view individualy for specific ajax calls and also get their context for the aggregating view.

  • render_to_response
  • ajax
  • decorator
  • rendering
Read More

Cached lookup model mixin

This mixin is intended for small lookup-style models that contain mostly static data and referenced by foreign keys from many other places. A good example is a list of Payment options in an e-shop that is referenced from Orders and is hitting database `order.payment` at least one time for an order. The idea is to cache entire table in a dict in memory that will live for entire life of a whole process serving many requests. The downside is that you need to restart the server when a cached lookup table changes.

  • foreignkey
  • cache
  • lookup
  • parent
Read More

Unobtrusvie Foldable Admin Interface

Inspired by [snippet 550](http://www.djangosnippets.org/snippets/550/), this allows you to expand or collapse apps in the main Admin screen. Requires jQuery. If jquery.cookie.js is available it will remember which apps you have expanded. Recommended usage: Place the JavaScript in a file called `admin-expand.js`. Create `templates/admin/base_site.html` in your templates directory (which is also a good place to [brand your Admin](http://djangobook.com/en/1.0/chapter06/#cn70)). Put the following code near the top, and you're done (adjusting file paths as needed). {% extends "admin/base.html" %} {% block extrahead %} <script type="text/javascript" src="jquery-latest.js"></script> <script type="text/javascript" src="jquery.cookie.js"></script> <script type="text/javascript" src="admin-expand.js"></script> {% endblock %}

  • admin
  • jquery
Read More

OpenID Form Field

**This is a newforms field for OpenID 1 & 2.** It normalizes and validates OpenID identifiers according to the [spec](http://openid.net/specs/openid-authentication-2_0.html#normalization): * `xri://=joelwatts` to `=joelwatts` * `joelwatts.com` to `http://joelwatts.com/` * `www.joelwatts.com` to `http://joelwatts.com/` An identifier that is well-formed, but not an OpenID (e.g. `example.com`), will cause a validation error. Requires [Python OpenID Library](http://openidenabled.com/python-openid/) 2.x.x.

  • newforms
  • fields
  • forms
  • form
  • field
  • openid
  • openid2
  • inames
  • identity
Read More

Zope testing django layer

[zope.testing](http://pypi.python.org/pypi/zope.testing/) is a test framework and test runner, similar to the django test runner and nose. This snippet is a [Layer](http://pypi.python.org/pypi/zope.testing/3.5.1#layers) class which you can assign as a layer attribute of your test suite to initialise and clean up the django test environment appropriately and to reset the test database between tests. for example: tests/suite.py import unittest from zope.testing import doctest def test_suite(): suite = doctest.DocFileSuite("models.txt") suite.layer = DjangoLayer return suite runtests.py import os from zope.testing import testrunner os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings' defaults = [ '--path', 'tests', '--tests-pattern', '^suite$', '-c' ] testrunner.run(defaults)

  • testing
  • tests
  • test
  • zope.testing
Read More

require XMLHttpRequest view decorator

Decorator to make a view only accept requests from AJAX calls. Usage:: @require_xhr() def my_view(request): # Returns data # ... by [skam](http://skam.webfactional.com/)

  • ajax
  • views
  • view
  • decorator
  • decorators
  • xhr
  • xmlhttprequest
Read More

Admin list_display Ajax

Sometimes it can be time consuming to go through a bunch of objects in Django's Admin if you only need to update one field in each. An example of this is an `order` field that allows you to manually set the order for a queryset. **This snippet contains examples of how to set up the Admin list_display to make Ajax calls to a custom view.** The following code may not be worthy of being a snippet, it's all pretty straightforward, but here it is for those who just want to copy-and-paste.

  • admin
  • jquery
Read More

HTML Prettifier

Tired of scrolling through hundreds of lines of code where the indentation is maddening? Here's a middleware class that prettifys your html markup so it's nice and consistently indented. Intended only for debugging, and I add it to the middleware stack conditionally on TEMPLATE_DEBUG. Requires BeautifulSoup.

  • html
  • pretty
  • prettify
  • ugly
  • indented
Read More

Color SQL logging middleware

Yet another SQL logger, this time with color and tresholds. By default it will only print a summary line (total time, query count) unless one of the tresholds (total time, query count, individual query time) was exceeded. You may use LOG_COLORSQL_VERBOSE = True to get the raw SQL for all requests regardless of any configured tresholds. In either case the middleware will highlight problematic areas in yellow or red. If you don't like the colors you can either set your tresholds to really high values, edit the code, or use a different middleware. :-)

  • sql
  • middleware
  • log
Read More
Author: moe
  • 4
  • 13

A custom 500 handler which is AJAX-aware

The default 500 handler does not take into consideration if the HTTP request made is an XMLHttpRequest. If it's an XHR, then it may not be a good idea to send back your default 500 HTML page. To use this custom 500 handler, just add the following to your urls.py: handler500 = 'my_project.my_app.views.my_500'

  • ajax
  • 500
  • handler
  • httprequest
Read More

Regrouping admin models

This is modification of Django's original adminapplist template tag. You can move your models from one app to other or completely hide them with this mod. Copy django_dir/contrib/admin/templates/admin/index.html file to your templates/admin folder, open it, then change {% load adminapplist %} to {% load custom_adminapplist %} (or whatever you named the templatetag file) After that, write your regrouping schema to settings.py file like this; UPDATED, now using tupples instead of dicts in APP_SCHEMA to make it more DRY. ` APP_SCHEMA=[ ( ['Model','List'], 'From App', 'To App', ), ( ['FlatPage'], 'Flatpages', 'Site Content', ), ( ['Product'] 'Product', 'Shop', ), ( ['Site'] 'Sites', #We are hiding Site model by not defining a target. ), ] `

  • templatetag
  • models
  • admin
  • app
Read More