Login

All snippets

Snippet List

Message exception

This exception is util when you want to raise an exception but want its message be shown as a message to the user, with no error 500 or 404 pages. To use it, just append the middleware in the MIDDLEWARE_CLASSES setting and raises HttpMessage when necessary.

  • http
  • redirect
  • message
  • exception
Read More

SizeAndTimeMiddleware

Used for showing size of the page in human readable format and time taken to generate the page on the server. To use it, in your base template, somewhere put the line: `<!-- ____SIZE_AND_DATE_PLACEHOLDER____ -->`. May be used on production.

  • middleware
Read More

minimal nginx conf to split get/post requests

After a point the sql server becomes the bottleneck in lots of web application, and to scale, master-slave replication with single master, multiple slave is recommended. This setup with nginx can be used to accomplish traffic distribution between master and slave based on request method.

  • middleware
  • nginx
  • loadbalancing
  • master-slave
Read More

ajax error sink

Often its useful to get error information for ajax/javascript errors happening on various clients. This can go to something like this: # error_sink def error_sink(request): # post request, with event name in "event", and event data in "data" context = request.REQUEST.get("context", "") context = cgi.parse_qs(context) context["data"] = cgi.parse_qs(context.get("data", [""])[0]) context["user"] = request.vuser context["referrer"] = request.META.get('HTTP_REFERER', "referrer not set") context = pformat(context) send_mail( "ajax error", context, "[email protected]", ["[email protected]",], fail_silently=True ) return JSONResponse({"status": "ok" }) # }}}

  • ajax
  • jquery
  • error
  • reporting
Read More

better paginator template tag

This is slight improvement over [Paginator|Snippet 73](http://www.djangosnippets.org/snippets/73/). That used to not work properly if querystring already contains other parameters, like search result page. website/paginator.html: <br /><center> <span class="lbottom"> {% if has_previous %}<a href="{{ path }}page={{ previous }}"><< Previous </a>{% else %}<span>Previous </span>{% endif %} {% if show_first %}<a href="{{ path }}page=1">First </a>{% endif %} {% for page_no in page_numbers %} {% ifnotequal page_no page %} <a href="{{ path }}page={{ page_no }}">{{ page_no }} </a> {% else %} {{ page_no }} {% endifnotequal %} {% endfor %} {% if show_last %}<a href="{{ path }}page={{ pages }}">Last </a>{% endif %} {% if has_next %}<a href="{{ path }}page={{ next }}">Next >></a>{% else %}<span>Next </span>{% endif %} </span> <br /></center>

  • templatetag
  • paginator
Read More

set_paths

To make all scripts relocatable. The layout of my project is: /some/path/myproject/ /some/path/myproject/some_script /some/path/myproject/some_other_script /some/path/myproject/set_paths.py /some/path/myproject/setttings.py /some/path/myproject/lib/ # some external libraries/apps checked in with my project. /some/path/myproject/myapp/ # my apps etc. This way myproject folder can be moved anywhere on the file system, and calling right path, settings.py is used.

  • django
  • cron
  • scripts
Read More

send_html_mail

There are many versions, this is the one I like. This is quite generic, can auto generate text version of the mail if required.

  • html-mail
Read More

ajax_validator generic view

Sample jQuery javascript to use this view: $(function(){ $("#id_username, #id_password, #id_password2, #id_email").blur(function(){ var url = "/ajax/validate-registration-form/?field=" + this.name; var field = this.name; $.ajax({ url: url, data: $("#registration_form").serialize(), type: "post", dataType: "json", success: function (response){ if(response.valid) { $("#"+field+"_errors").html("Sounds good"); } else { $("#"+field+"_errors").html(response.errors); } } }); }); }); For each field you will have to put a div/span with id like fieldname_errors where the error message will be shown.

  • ajax
  • javascript
  • view
  • generic
  • jquery
  • validation
  • form
Read More

Firebug Lite Middleware

This middleware allows you to easily include the excellent debugging tool Firebug Lite in your projects. To install it, just add the middleware class to your list of installed middleware, pretty much anywhere in the list. If DEBUG is True, and your IP address is in the list of INTERNAL_IPS, Firebug Lite will load. It will, however, only load in browsers that are **not** Firefox, as I'm assuming that you have the **real** Firebug installed in Firefox. If you don't, go install it--what's wrong with you? Check out http://getfirebug.com/lite.html for more information.

  • middleware
  • debug
  • ie
  • debugging
  • firebug
  • msie
Read More
Author: jfw
  • 8
  • 15

View and StatefulView classes

This snippet provides two view classes. The two reason I wanted to write this are, 1) Not have to import all the boilerplate code for each view and 2) so I could have the same URL handle loading a persons profile, or handle an OpenID login request without having to write two separate views. (Yes I know it isnt to hard to write my view, check the header and pass it off to the proper handler view, but I think it looks better code wise to have the handler methods all in one class) The first one is just for normal views conveniently called *View*. The *View* class that lets you do at least 90% of what you can do in a normal view function, but without having to import all the normal boilerplate code first since this class wraps methods around most if not all the *HttpResponse* types. The second class *StatefulView* maintains its state across page loads This is especialy useful for ajax type calls where you wish to maintain some form of state while the user is doing something but do not wish to make DB calls and do not wish to polute the session with trivial things **Note:** On my system it maintains state across browsers and computers as it is not tied to the session, BUT for this to happen all requests must be handled by the same proccess. So requests going to a differing process with not have the state maintained.

  • views
  • class
  • stateful
Read More

django_stateful

this snippet provides a class that can be subclassed for creating views that retain state between requests, you can read more here http://code.google.com/p/django-stateful/ your comments are welcome!

  • django
  • stateful
  • seaside
  • continuations
Read More

Cachable Class Method Decorator

This decorator does automatic key generation and simplifies caching. Can be used with any class, not just model subclasses. Also see [Stales Cache Decorator](http://www.djangosnippets.org/snippets/1131/).

  • cache
  • decorator
Read More

Use the primary key in FileField and ImageField filenames

Sometimes it is desirable to use values like the primary key when naming `FileField` and `ImageField` files, but such values are only available after saving the model instance. This abstract class implements a two-phase save in order to make this case easy. See the example in the docstring. Another solution would be to write a `save()` that requires `upload_to` to be a callable that checks for `instance.pk`, then calls it again after saving. However, this would require more work from the developer for simple cases.

  • imagefield
  • filefield
  • rename
  • upload_to
Read More

3110 snippets posted so far.