Login

Top-rated snippets

Snippet List

Send templated email with text | html | optional files

Use this to send emails to your users, takes one template and renders it as html or text as needed. Credits to """ Jutda Helpdesk - A Django powered ticket tracker for small enterprise. (c) Copyright 2008 Jutda. All Rights Reserved. See LICENSE for details. lib.py - Common functions (eg multipart e-mail) """ MIT licence I only removed the specific project parts and made it general to use. The original project repository https://github.com/rossp/django-helpdesk/

  • template
  • email
  • function
Read More

Generic admin action export selected rows to excel

Based on [http://djangosnippets.org/snippets/1697/](http://djangosnippets.org/snippets/1697/) but improved with multiline fields, and unicode chars. Also it generates an xls file, not a csv one. Requires, pyExcelerator *Usage:* Add the code to your project, e.g. a file called actions.py in the project root. Register the action in your apps admin.py: from myproject.actions import export_as_xls class MyAdmin(admin.ModelAdmin): actions = [export_as_xls]

  • export
  • admin-actions
  • xls
Read More

Password Validation - Require Letters and Numbers - no regex

Simple password validation for user registration - requires that password be 7 or more characters and contain both letters and numbers. Original validation with regex approach developed by kurtis. Optimized no-regex version based on code from watchedman ran as fast or significantly faster on all systems on which we tested it.

  • registration
  • model
  • regex
  • user
  • validation
  • form
  • password
Read More

Decorating URL includes

Apply a decorator to every urlpattern and URLconf module returned by Django's include() method . This allows you use a decorator on any number of views without having to decorate each one individually. The use case here is wrapping all of the Django Admin with a superuser decorator. This is code that's better left alone where we can't actually go in and decorate the Admin views and urlpatterns manually. It's also almost guaranteed the Admin will include() other URL files. So the added bonus is all the INSTALLED_APPS that have their admin.py files registered by admin.autodiscover() will be decorated automatically as well. This snippet is greatly inspired by [@miracle2k](http://djangosnippets.org/users/miracle2k/)'s excellent [#532](http://djangosnippets.org/snippets/532/). In the comments there @timbroder offers a modification to decorate includes but I think this is cleaner, simpler code and not subject to changes in the Django base code driving _get_url_patterns().

  • urls
  • urlconf
  • decorator
  • urlpatterns
  • resolve
Read More

keeping filter states after edits

When saving an edit to an object from a filtered list view you are, by default, returned to list view without any of your filters applied. This solves that problem, keeping the filtered view in a session variable until you reach a point where the session key is deleted. The solution presented here is hugely based off of other's work with most of the solution gained from: [Admin: return to change_list with filter and pagination applied](http://djangosnippets.org/snippets/2415/ "Admin: return to change_list with filter and pagination applied") This solution offered the best approach in our mind over the others listed here on snippets since the solution didn't require changes to template code...this is completely self contained within your own admin.py files. The advantage to our solution over the above linked solution is that under different use cases the user may or may not be redirected to the filtered list_view. For example, if you edit an object and click the save and continue button, then you would lose the filter when you finally finished editing the object and clicked save. Added on here is a delete of the session key when users add objects, the reasoning we're going this route is we don't want to return users to filtered views when they just added a new object. Your mileage may vary and if so, it's easy enough to fit your own needs. HTHs

  • filter
  • admin
  • change_list
Read More

Cache view by user (and anonymous)

Use this decorator in your views to cache HttpResponse per user, so each user has his own cache, instead of a shared one as `from django.views.decorators.cache.cache_page` does. Add this to use: from somewhere import cache_per_user @cache_per_user(ttl=3600, cache_post=False) def my_view(request): return HttpResponse("LOL %s"%(request.user)) All documentation inside the decorator are in brazilian portuguese, feel free to translate to english

  • views
  • cache
  • decorator
Read More

Load File From URL Widget

Rather simple usage, modelforms/in the admin: class CustomAdminForm(forms.ModelForm): class Meta: model = Something widgets = { 'image': URLFileInput(default_exts=[".png", ".gif", ".jpg"]), } class SomethingAdmin(admin.ModelAdmin): form = CustomAdminForm admin.site.register(Something, SomethingAdmin) Basically, this will pull the image from the URL instead of only pulling it from your harddrive for upload. Also accepts optional default_exts argument which limits the file types. Defaults to images.

  • imagefield
  • filefield
  • urlfield
Read More

filter for simplifying creating data URI´s

This filter will return data URI for given file, for more info go to: [wikipedia](http://en.wikipedia.org/wiki/Data_URI_scheme) Sample Usage: ` <img src="{{ "/home/visgean/index.png"|dataURI }}"> ` will be filtered into: ` <img src="data:image/png;base64,iVBORw0..."> ` This is good for small images.

  • filter
  • mime
  • uri
  • data URI
Read More

Class based view decorator

Converts a passed decorator to one that can be applied to a class based view (ie. automatically decorates dispatch). This means no more overriding dispatch for every view / request method you want to apply decorators to. Works in Django 1.3 but I suspect it probably works in 1.2 as well.

  • django
  • generic-views
  • decorator
  • class-based-views
Read More

Generic model filter from request GET data

You just use standart django query terms, for example: <form> <input class="field_text filter_from" type="text" name="cost__gte" placeholder="from" value="{% if request.GET.cost__gte %}{{ request.GET.cost__gte }}{% endif %}"> <input class="field_text filter_to" type="text" name="cost__lte" placeholder="to" value="{% if request.GET.cost__lte %}{{ request.GET.cost__lte }}{% endif %}"> </form> model: class Object(models.Model): cost = models.IntergerField() objects = ObjectManager()

  • filter
  • forms
  • queryset
Read More

LoginRequired class-based view decorator

Apply the `login_required` decorator to all the handlers in a class-based view that delegate to `cls.dispatch`. Optional arguments: * redirect_field_name = `REDIRECT_FIELD_NAME` * login_url = `None` See the documentation for the [`login_required`](https://docs.djangoproject.com/en/dev/topics/auth/#the-login-required-decorator) method for more information about the keyword arguments. Usage: @LoginRequired class MyListView (ListView): ...

  • view
  • decorator
  • class
  • login_required
  • class-decorator
  • class-based-views
Read More

django app name & breadcrumbs l10n

This approach allows you to rename you app name & app breadcrumbs within admin interface. Paste the code in admin.py of your application and change AppLabelRenamer.main params.

  • admin
  • applications
  • admin-interface
  • breadcrumbs
Read More

Effective content caching for mass-load site using redirect feature

Hi All, I would like to share my idea and experience in using http redirect feature to organize effective content caching and avoid site blocking on mass requests to not yet cached content. First of all, I should explain that I don't mean usual template-based pages, whose caching in django is enough in almost all cases. My speech is concerning to content such as dynamically created images, external files and other content which may require almost unpredictable long time period to be ready, up to about 10 seconds. Anyway, the content which is already in cache, can be returned immediately. The question is - what *should* happen if the requested content is *not yet present* in the cache? The HTML content is not a problem in this case - we can return intermediate page with meta information to ask a client to retry the content after some period of time. But non-HTML content, such as image, or json, is a problem. The usual *blocking* behavior of the django caching subsystem is not appropriate in a case when the content preparation process takes *more than several fractions* of a second. The whole period while the content is preparing (painting, getting from the external resource and so on) *hundreds* of users will *ask not yet cached* content until all available application server connections will be *occupied* by waiting requests and new user will wait for the content even if the content requested by him is actually ready to be returned. The celery package resolves this problem *partially*, allowing to schedule cache update before cache expiration in asynchronous manner (I am using threadpool package for this purpose instead), and avoiding blocking on content preparation procedure, but the problem with not yet available content remains unresolved. We might schedule periodic cache update to avoid such a situation, but this way leads to unnecessary resource load and may be inappropriate at all in some cases, f.e. for the service like CloudMade or Google "staticmap" painting map content basing on the request parameters. My solution is *using HTTP Redirect feature* . Ideal solution would be available if most of HTTP clients supported Retry-After header in the HTTP Redirect response. Unfortunately, no one of most popular clients (neither Mozilla, nor IE, nor Chrome) does it. Really they ask redirected URL immediately after receiving the redirection response, and ignore Retry-After header at all. Anyway, I hope that they *will* support this feature, but this is not enough right now. So, instead of delegating waiting job to the client side, we need to organize waiting on the server. For this purpose I have created small separate application server with it's *own connection pool*, and delegated waiting task to him (see the snippet). This server needs one URL (/retry_after in the example) looking to the view above, installed in the url.py, and additional DEFAULT_RETRY_TIMEOUT parameter in the settings.py. The view uses request GET parameters, so Django will not try to cache it's results. The only task for this server is to *suspend* redirected requests until requested time is *really arrived*, and then redirect the request to the original URL. To make possible to process many requests simultaneously, it breaks waiting and redirects too long time requests to the self basing on the default timeout. Using this server is simple. We will instantiate the 'retry' server on the separate URL as a *separate application server* and will redirect all requests required to be delayed to this server, passing original URL and the time moment when the requested content should be ready, as parameters. The main server which prepares and returns the content, is *never waiting*. It returns prepared content from the cache, if it is found there, or *starts* content preparation process in *asynchronous* manner using threads, celery package, or any other appropriate technique, and *immediately redirects* the request to the 'retry' server The following is a fragment of the code using 'retry' server: ... # Create your views here. def jams(request,z,x,y): jams_timeout = settings.JAMS_TIMEOUT retry_after_server = settings.RETRY_AFTER_SERVER try: jams_ts,jams_png = request_jams(z,x,y) except Http404,ex: return HttpResponseNotFound() if not jams_png: if settings.DEBUG: logger.debug("JAMS NOT YET READY FOR: %s" % str((z,x,y))) # Tell a client to retrieve jams later time_after = time.time() + settings.DEFAULT_RETRY_TIMEOUT if settings.DEBUG: logger.debug("SEND RETRY AFTER FOR: %s" % str((z,x,y))) loc = reverse(jams,args=(z,x,y)) if request.get_host(): loc = request.build_absolute_uri(loc) r = HttpResponseRedirect( retry_after_server + '?' + urlencode({'redirect': loc,'retry_after':int(time_after)}) ) r['Retry-After'] = settings.DEFAULT_RETRY_TIMEOUT return r # return a png got from the cache if settings.DEBUG: logger.debug("RETURNING JAMS FOR: %s" % str((z,x,y,http_date(jams_ts),http_date(time.time())))) r = HttpResponse(jams_png) r['Content-Type'] = "image/png" r['Content-Length'] = len(jams_png) r['Content-Location'] = request.path # extra data for cache negotiation # Common and ConditionalGet Django Middleware will do the rest r['ETag'] = '"%s"' % md5_constructor(jams_png).hexdigest() r['Last-Modified'] = http_date(jams_ts) r['Expires'] = http_date(jams_ts + jams_timeout) return r ... At the application level, the request_jams() call tries to get content from the cache, and starts content update process asynchronously if required. It returns content got from the cache, and timestamp when the content has been created last time, or pair of None,None values, if the requested content is not available immediately. The line starting from 'r = HttpResponseRedirect' redirects the request to the 'retry' server, if the content is not available immediately. I am using nginx as a 'front-end' proxy server which passes requests to two separate fastcgi daemons - 'retry' and main django application servers separating requests by prefix. The following is a fragment of the nginx.conf configuration file for the nginx server: server { ... location /jams { fastcgi_pass unix:/var/tmp/jams.sock; ... } location /retry_after { fastcgi_pass unix:/var/tmp/retry.sock; ... } ... } As you can see, two locations are passed to *different* application server instances in the production environment, so they *don't block each other*. Really they both are implemented inside one django project, and started from the same directory as fastcgi daemon instances with different starting parameters (sockets to listen, log files etc.). I've used such structure to configure and debug my server easy, either just starting one developer server for both locations, or to have a possibility to start production server in described 'split' mode on the other hand. You can see that the both servers (jams and retry) use the same DEFAULT_RETRY_TIMEOUT setting from the settings.py file. The DEFAULT_RETRY_TIMEOUT plays role of load balancing parameter for requests which wait finishing asynchronous job. After the retry timeout is passed, the control returns to the client by the redirection response (or, for smart clients, the client itself waits the retry timeout before requesting the resource again), so the server may cleanup resources temporary acquired by these requests. Additional bonus of using such technique is stability of server processor load. Even in prime time, the server load is stable and controlled: number of the application instances and number of threads in the thread pool (evaluating asynchronous jobs) for each instance is fixed by configuration, nginx load per request is minimal, and concurrent requests are balanced (between server, network, and clients) by the retry timeout and redirect responses. You can see the result of the work on the our site, f.e. [on this page](http://www.doroga.tv/nnov/apps/map/), where all (transparent version) jam tiles are painting such a manner. The only difference for the production server environment is that some top zooms of most popular regions are refreshed by the special daemon (also written using django as a 'management command') which forces tiles to be refreshed in the cache even no one client requests it right now — to decrease response time for the jams map after long 'sleep' period.

  • cache
  • load
  • redirect
  • nginx
  • content
  • mass
Read More

Method Caching

A very simple decorator that caches both on-class and in memcached: @method_cache(3600) def some_intensive_method(self): return # do intensive stuff` Alternatively, if you just want to keep it per request and forgo memcaching, just do: @method_cache() def some_intensive_method(self): return # do intensive stuff`

  • memcache
  • cache
  • decorator
  • memcached
  • decorators
  • caching
Read More

3110 snippets posted so far.