Login

All snippets

Snippet List

Extended JSON encoder

The Django JSON encoder already extends the `simplejson` encoder a little; this extends it more and gives an example of how to go about further extension. Hopefully `newserializers` (see the community aggregator today) will supercede this, but until then, it's useful.

  • serialize
  • json
  • serializer
Read More

DebugFooter middleware with Pygments sql syntax highlighting

Based on Snippet [766](http://www.djangosnippets.org/snippets/766/) but added syntax highlighting of the sql output via [pygments](http://pygments.org/). The sql output will also be wrapped at 120 characters by default (can be configured by changing WRAP). It degrades nicely if pygments is not installed. This will add quite some cpu-cycles just for printing debug messages so use with care. Following is the rest of the original description by [simon](http://www.djangosnippets.org/users/simon/) (shamelessly copied): Adds a hidden footer to the bottom of every text/html page containing a list of SQL queries executed and templates that were loaded (including their full filesystem path to help debug complex template loading scenarios). To use, drop into a file called 'debug_middleware.py' on your Python path and add 'debug_middleware.DebugFooter' to your MIDDLEWARE_CLASSES setting. Edit: Added the ability to set the height of the debug-box

  • sql
  • middleware
  • debugging
Read More

SectionedForm

Sometimes we need divide forms in fieldsets, but this make us declare all fields in HTML template manually. This class is to help you to do this by a easy way. **How to use** First, download this file as name "sectioned_form.py" Later, turn your form inherited from the class **SectionedForm**, override method "_html_output" and declare fieldsets and fieldset_template attribute, like below: from sectioned_form import SectionedForm class MyForm(forms.ModelForm, SectionedForm): fieldsets = ( (None, ('name','age','date')), (_('Documents'), ('number','doc_id')), ) fieldset_template = "<h2>%s</h2>" def _html_output(self, *args, **kwargs): return SectionedForm._html_output(self, *args, **kwargs)

  • newforms
  • forms
  • form
  • formset
Read More

Timing Django Requests

Adds an 'X-Django-Request-Time' HTTP response header that times how long django spent processing the request.

  • middleware
  • http
  • headers
  • profiling
Read More

Default settings for a app

Save this as conf.py in the app's directory. Now you can do `from myapp.conf import settings`. You can access from the imported object every item of your settings.py including the default settings of myapp. Though you don't have to define every setting in settings.py you use in your app. Now you can ommit annoying try...except statements to define defaults directly in the code.

  • settings
  • conf
  • app
Read More

Verbose template filter : avoid too many if

This tiny template filter saves you the tedious test "if this variable is set, print this text based on this variable". 'verbose' filter takes one parameter : a string containing '%s' which is a placeholder for the value to test. Check those examples : * Replace this : {% if name %} Hello {{ name }}, this is a dummy text {% endif %} * By this : {{ name|verbose:"Hello %s this is a dummy text" }} This is also usefull for HTML : {{ image|verbose:"<img src=\"%s\" />" }}

  • template
  • filter
Read More

MintCache (simple version)

This is intended as an alternative to http://www.djangosnippets.org/snippets/155/ Put this in your own cache.py and import it instead of django.core.cache and use it the same way. We left out the "add" function but it shouldn't be too hard to make if you want it. From the above post: "The purpose of this caching scheme is to avoid the dog-pile effect. Dog-piling is what normally happens when your data for the cache takes more time to generate than your server is answering requests per second. In other words if your data takes 5 seconds to generate and you are serving 10 requests per second, then when the data expires the normal cache schemes will spawn 50 attempts a regenerating the data before the first request completes. The increased load from the 49 redundant processes may further increase the time it takes to generate the data. If this happens then you are well on your way into a death spiral MintCache works to prevent this scenario by using memcached to to keep track of not just an expiration date, but also a stale date The first client to request data past the stale date is asked to refresh the data, while subsequent requests are given the stale but not-yet-expired data as if it were fresh, with the undertanding that it will get refreshed in a 'reasonable' amount of time by that initial request."

  • cache
  • memcached
  • caching
  • mintcache
Read More

Django newforms ExtJS JSON Encoder

This is a subclass of Django's built-in JSONEncoder that adds the ability to output form and field objects as ExtJS-compatible config objects. Simple example: from django.utils import simplejson json = { 'data': [], 'success': True, 'metaData': { 'fields': SFY09RDOForm(), 'root': 'data', 'successProperty': 'success' }, } return HttpResponse(simplejson.dumps(json, cls=ExtJSONEncoder)) Where SFY09RDOForm is a subclass of django.forms.Form. 6/20/2008: Updated to pass on the help_text parameter (useful in combination with this override in ext: http://extjs.com/forum/showthread.php?t=36642)

  • json
  • ext
  • encoder
  • extjs
Read More

Generic CSV Export

This will generically add csv exporting to your views in the admin. It will default to exporting the entire table you see (without paging). If the table only has one column, it will export the fields the the model. You can overide this functionality. I ended up creating my own admin/change_list.html to apply this functionality universally: {% extends "admin/base_site.html" %} {% load adminmedia admin_list i18n %} {% block stylesheet %}{% admin_media_prefix %}css/changelists.css{% endblock %} {% block bodyclass %}change-list{% endblock %} {% if not is_popup %}{% block breadcrumbs %}<div class="breadcrumbs"><a href="../../">{% trans "Home" %}</a> &rsaquo; {{ cl.opts.verbose_name_plural|capfirst|escape }}</div>{% endblock %}{% endif %} {% block coltype %}flex{% endblock %} {% block content %} <div id="content-main"> {% block object-tools %} <ul class="object-tools"> <li><a href="csv/{%if request.GET%}?{{request.GET.urlencode}}{%endif%}" class="addlink">Export to CSV</a></li> {% if has_add_permission %} <li><a href="add/{% if is_popup %}?_popup=1{% endif %}" class="addlink">{% blocktrans with cl.opts.verbose_name|escape as name %}Add {{ name }}{% endblocktrans %}</a></li> {% endif %} </ul> {% endblock %} <div class="module{% if cl.has_filters %} filtered{% endif %}" id="changelist"> {% block search %}{% search_form cl %}{% endblock %} {% block date_hierarchy %}{% date_hierarchy cl %}{% endblock %} {% block filters %}{% filters cl %}{% endblock %} {% block result_list %}{% result_list cl %}{% endblock %} {% block pagination %}{% pagination cl %}{% endblock %} </div> </div> {% endblock %}

  • admin
  • export
  • csv
Read More

Simple views method binding

@match_func_by_method def frontpage (request) : pass def get_frontpage (request, argument, ) : # GET things pass def post_frontpage (request, argument, ) : # POST things pass

  • views
  • http-method
Read More

CSVImport

This is an awesome script! The original can be found here: http://www.djangosnippets.org/snippets/633/ I had to make a couple minor changes to get it working for me, so I thought I would share the love...

  • csv
  • import
Read More

Image gradients on the fly

A Django view to create an image gradient on the fly as a PNG file. The direction, size and colors of the gradient a specified in the filename and extracted by Django in the urls.py. Example usage from CSS: `background: url(/gradient-down-255,255,255-to-0,0,0-70-of-120.png) repeat-x;` creates a 70-pixel vertical gradient as background from white to gray. No static images needed. To modify, nothing but the CSS needs to be edited.

  • image
  • gradient
  • background
Read More

P3P Headers for iframes

This is nothing fancy and hasn't much to do with django itself, I just searched for this information for quite a while and thought it may be useful for others. If you use IE7 (and maybe IE6), it will block cookies in iframes, if the iframes content comes from another server (quite common, I think). The P3P specification lets you declare your privacy settings in a format interpretable by browsers, essentially you can tell IE that you adhere to "don't be evil", and are allowed to handle cookies afterwards. I don't think that makes much sense, but it seems that it is the only way to make IE accept cookies in iframes. I had no idea that django made it that incredibly easy to "patch" the response-header, but it does! :)

  • p3p
  • ie7
  • internet
  • explorer
  • iframe
  • privacy
Read More

AgreementField

Creating new field to handle checkbox validation in situations where the checkbox must be checked, as in check to agree to terms and such. Thanks to Daniel Pope for the [suggestion](http://code.djangoproject.com/ticket/5957#comment:7) on Django Trac Ticket #[5957](http://code.djangoproject.com/ticket/5957)

  • newforms
  • checkbox
  • forms
  • validation
  • clean
  • booleanfield
  • agreement
Read More

3109 snippets posted so far.