Login

Most bookmarked snippets

Snippet List

Automatic Memoization Decorator

This decorator will memoize the results of instance methods, similar to `django.util.functional.memoize`, but automatically creates a cache attached to the object (and therefore shares the life span of the object) rather than requiring you to provide your own. Note this is intended for instance methods only, though it may work in some cases with functions and class methods with at least one argument. This is useful for memozing results of model methods for the life of a request. For example: class MyModel(models.Model): #Fields here @auto_memoize def some_calculation(self): #some calculation here return result

  • cache
  • memoize
Read More

Generic CSV export admin action factory with relationship spanning fields and labels

Based on [#2712](../2712/) "This snippet creates a simple generic export to csv action that you can specify the fields you want exported and the labels used in the header row for each field. It expands on #2020 by using list comprehensions instead of sets so that you also control the order of the fields as well." The additions here allow you to span foreign keys in the list of field names, and you can also reference callables.

  • admin
  • generic
  • export
  • csv
  • admin-actions
  • export-csv
Read More

Add get_addr() method to request object

I thought it would be useful to have a `get_addr()` method available on request objects, similar to the `get_host()` provided by Django. This middleware will add a `get_addr()` method to requests which uses the `X-Forwarded-For` header (useful if you're behind a proxy) if it's present and you have the `USE_X_FORWARDED_FOR` header set to `True` (default is `False`) and otherwise will use the `REMOTE_ADDR` environment variable. Note that if you are *not* behind a proxy and have `USE_X_FORWARDED_FOR` set to `True`, then clients can spoof their IP by simply setting the `X-Forwarded-For header`.

  • request
  • ip
  • header
  • address
  • client
  • remote-addr
  • x-forwarded-for
  • get-addr
Read More

Automatically generate admin

A management command to automatically generate a fully specified admin for the models in a specific app. It automatically generates raw_id_fields, search_fields, list_filter and more. It bases this on date fields, fields named as "name" or slug. Usage: ./manage admin_autogen <model>

  • django
  • scaffold
  • auto
  • django-admin
  • automatic
  • generation
  • generate
Read More

QRCode template tag

I had a hell of a time getting most QR code stuffs out there working with Django. Many projects, but problems here and problems there. The only additional code you'll need for this is to "pip install qrcode". After that, you're free to <img src="{% qrcode_datauri "http://localhost:8000/" %}" />.

  • qrcode
Read More

CheckboxMultiSelect with interable checkboxes

A widget for a checkbox multi select, adapted from the RadioSelect widget, which allows you to iterate over each choice in the template rather than outputting the whole thing as a ul in one go. {{ form.field.label_tag }} {% for option in form.field %} <span>{{ option }}</span> {% endfor %}

  • checkbox
  • forms
  • widget
Read More

Google v3 geocoding for Geodjango admin site

This only works with Point geometry. [video](http://www.youtube.com/watch?v=gZ7_n177sTE&list=HL1351725584&feature=mh_lolz) Rename the snippet as gmgdav3.js and save it to template/admin with [gmgdav3.html](http://djangosnippets.org/snippets/2840/) * - *models.py*: ` from django.contrib.gis.db import models` ` class point(models.Model):` ` address = models.CharField(max_length=100, help_text='Press "Tab" to refresh the map')` ` longitude = models.FloatField(help_text='WGS84 Decimal Degree. Press "Tab" to refresh the map')` ` latitude = models.FloatField(help_text='WGS84 Decimal Degree. Press "Tab" to refresh the map')` ` in_geom = models.PointField('shp', srid=4326)` ` objects = models.GeoManager()` ` def __unicode__(self):` ` return str(self.address)` * - *admin.py*: ` from models import * ` ` from django.conf import settings` ` from django.contrib.gis import admin` ` from django.contrib.gis.geos import GEOSGeometry` ` class GoogleAdmin(admin.OSMGeoAdmin):` ` g = GEOSGeometry('POINT (9.191884 45.464254)') # Set map center` ` g.set_srid(4326)` ` g.transform(900913)` ` default_lon = int(g.x)` ` default_lat = int(g.y)` ` default_zoom = 7` ` extra_js = ["http://maps.google.com/maps/api/js?v=3.2&sensor=false"]` ` map_template = 'gmgdav3.html'` ` admin.site.register(point, GoogleAdmin)` ` # admin.site.register(your other models...,...)`

  • admin
  • google-maps
  • geocode
  • geolocation
  • geodjango
Read More

Generic admin action export selected rows to excel

Based on [Snippet 2558](http://djangosnippets.org/snippets/2558/) but without saving the generated file to disk before downloading. 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]`

  • admin
  • export
  • admin-actions
  • xls
Read More

HTTPS redirections middleware with updated URL template tag

This middleware redirects HTTP requests to HTTPS for some specified URLs, in the same way as [85](http://djangosnippets.org/snippets/85/). It also changes the `url` template tag to use the `https` scheme for the same URLs. For example, if you have the following URL pattern: url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'https': True}) then the template: {% from future import url %} {% url 'django.contrib.auth.views.login' %} will render: https://host.example.com/accounts/login/ and any plain HTTP requests to /accounts/login get redirected to HTTPS. URL patterns not marked with `'https': True` remain unaffected. Notes: * The HttpRequest object must be present in the template context as `request`, so add `django.core.context_processors.request` to `TEMPLATE_CONTEXT_PROCESSORS` and make sure to use `RequestContext`. * This snippet overrides the existing `url` template tag. Remove the last line and register the new `url` function properly, as a separate tag, if this makes you unhappy. You'd then have to change your templates to use it. * It would be nicer to change the way reverse look-ups behave instead of changing only the `url` template tag, but the URL resolver, and the `reverse` function, know nothing about requests, so have no way to find the correct host name.

  • middleware
  • template
  • url
  • ssl
  • reverse
  • https
  • redirection
  • tls
Read More
Author: xlq
  • 0
  • 2

Amazon S3 browser-based upload form(FIXED)

This is a 'fixed' version of snippet [1868](http://djangosnippets.org/snippets/1868/) Changes: *Correctly handle the Content-Type, because amazon requieres it to be named with a dash and we can't use dashes in the form attributes declaration. *Also added max_size handling, with the corresponding update to the policy generation. *Added an example usage with some javascript for basic validation. [See the amazon reference](http://aws.amazon.com/articles/1434?_encoding=UTF8&jiveRedirect=1)

  • s3
  • amazon
  • html form
  • upload form
Read More

Pre-delete signal function for deleting files a model

This snippit is meant to be used with the pre_delete signal to delete any files associated with a model instance before the instance is deleted. It will search the model instance for fields that are subclasses of FieldFile, and then delete the corresponding files. As such, it will work with any model field that is a subclass of FileField.

  • remove
  • delete
  • signals
  • file
Read More

Tastypie v0.9.11 LoginRequiredAuthorization

This is an Authorization class for [Tastypie](http://django-tastypie.readthedocs.org/en/latest/authentication_authorization.html) v0.9.11 (v0.9.12 changes how Authorization works). DjangoAuthorization checks specific permissions — `add_model`, `change_model`, `delete_model`, etc. If you don't need that level of permissions checking, this might be useful. It just makes sure the User is logged in. It's equivalent to the `login_required` decorator.

  • login_required
  • tastypie
Read More

3110 snippets posted so far.