Login

Top-rated snippets

Snippet List

Detect blog platform

Detect blog platform. As we all known, there are so many blog platform in the wild, e.g. Blogger.com, WordPress, LiveJournal, Movable Type etc. This little snippet could guess the blog platform according a url. Dependency: 1. pycurl 2. BeautifulSoup

  • detect
  • blog
  • type
  • platform
Read More

Ordered items in the database

First off: This snippet is more or less obsoleted by [snippet #259](/snippets/259/). The way that snippet #259 uses feels cleaner and more usable. It is basically the same code but the magic works a little bit different. In case you prefer this way, I've left this snippet as-is. Maybe you know this problem: you have some objects in your database and would like to display them in some way. The problem: the Django ORM does not provide any way to sort model instances by a user-defined criterion. There was already a plug-in in SQLAlchemy called [orderinglist](http://www.sqlalchemy.org/docs/plugins.html#plugins_orderinglist), so implementing this in Django was basically not a big deal. Usage is (due to use of meta-classes) quite simple. It is recommended to save this snippet into a separate file called `positional.py`. To use it, you only have to import `PositionalSortMixIn` from the `positional` module and inherit from it in your own, custom model (but *before* you inherit from `models.Model`, the order counts).

  • db
  • orm
  • database
  • plugin
  • mixin
Read More

Strip trailing .html extensions from URLs so that existing bookmarks work for a legacy site ported to Django

1) You've ported an existing web site to Django. 2) The new site URLs don't have html (or htm) extensions. 3) The old site had URLs with html extensions. 4) You want existing bookmarks to work. Use this middleware to removes trailing .htm and .html extensions from incoming URLs (GETs only) so that your new site honors existing bookmarks. Locate it in settings.MIDDLEWARE_CLASSES near CommonMiddleware because it has similar middleware stack location requirements. If an incoming URL has an html extension, ZapDotHtmlMiddleware strips it out and redirects.

  • middleware
  • url_rewrite
  • strip_dot_html_from_urls
Read More

Adding a field to a newform in __init__

When adding fields in the __init__ of a newform, and you don't want the fields to be added *after* the class-attribute fields, this is a possibility... This is a bad example as the email_from could just as well have been defined as a class variable!

  • newforms
  • field
  • init
Read More

Set Template Tag

Add a value to the context for easy access and for access from include templates. NOTE: This tag is composed from Django ticket: http://code.djangoproject.com/ticket/1322

  • tag
Read More
Author: Xin
  • 2
  • 3

Single Django App behind multiple Apache Proxies

** Django Proxied Behind Apache Path** Middleware and Context Processor for django applications behind a proxy like Apache's mod_proxy. Setting an HTTP header with the base path of the django application in the Apache mod_proxy configuration, we can pull that variable out of the request and adjust our template URIs and redirects. This allows us to serve the same Django application out from behind multiple VirtualHosts at different URL paths. Example use in templates: <a href="{{ base_path }}/login/">Login</a> Example Apache configuration: <LocationMatch ^/path/to/django/app/.*> RequestHeader set X-Base-Path "/path/to/django/app" </LocationMatch> RewriteRule ^/path/to/django/app/(.*) http://django-host:8080/$1 [P,L] In settings.py: VHOST_HEADER = "HTTP_X_BASE_PATH"

  • apache
  • virtualhost
  • mod_proxy
  • path
Read More

split filter

**Usage** (*in template*): <img src="{{ MEDIA_URL }}2007/images/{% filter split:","|random %}theimage1.jpg,something2.jpg,thirdisthecharm.jpg{% endfilter %}" /> I decided to make it simple, because one template creator wanted to add random images to different places of templates. Creating something huge, like external image filename parsing was not necessary in this case.

  • filter
  • split
Read More

Quickly check templates while sketching them out

This a small but very handy view that gives you a convenient direct access to your templates. Now suppose you saved the snippet under `misc.py`, it's critical to add this snippet (or a similar one, once you get the idea) to your `urls.py`: if settings.DEBUG: # Direct Templates urlpatterns += patterns('misc', (r'^template/(?P<path>.*)$', 'direct_to_template', {'template': '%(path)s'}), ) Now you are able to access any of your templates, in different directories by specifying their path after `template/`. e.g., http://example.com/template/news/index.html Of course you can change it as you want, you can also add other values to the dict argument, the only required key is `'template'`. The whole dict is made available in the template as a context. All GET parameters are made available in the template too. So `http://example.com/template/news/index.html?title=Testing Title` will make the `{{ title }}` var available in your template. So you can substitute basic variables quickly. This is was inspired by [django.views.generic.simple.direct_to_template](http://www.djangoproject.com/documentation/generic_views/#django-views-generic-simple-direct-to-template)

  • template
  • view
  • generic
Read More

Find nearby objects

This code assumes a) that you are using PostgreSQL with PostGIS and b) that the geometry column in your model's table is populated with points, no other type of geometry. It also returns a list instead of a QuerySet, because it was simpler to sort by distance from the given point and return that distance as part of the payload than to muck around with QuerySet. So bear in mind that any additional filtering, excluding, &c., is outside the scope of this code. 'Distance' is in the units of whatever spatial reference system you define, however if you do not intervene degrees decimal is used by default (SRID 4326, to be exact). To get distance in units a little easier to work with, use a spatial ref close to your domain set: in my case, SRID 26971 defines a projection centered around Illinois, in meters. YMMV.

  • gis
  • postgis
  • geography
  • geometry
  • nearby
  • nearest
  • distance
Read More

Changing field type in production

Assume a model called 'Child' with a field called 'schoolstd' whic h is of integer type and not null. You need to change it to char type and not null and the same time preserve the data. The above snippet does this in postgresql.

  • schema_evolution
Read More

More admin clock time increments

This is quite a hack (need to modify Django code), but relatively simple and stable. It displays various times in whichever increments and columns you specify, rather than just Midnight, Noon, Now & 6am. You can use it throughout your admin and newforms-admin code. This is a (slightly updated) copy of the ticket #1848 which wasn't included in trunk. http://code.djangoproject.com/ticket/1848

  • admin
  • time
Read More

Sanitize text field HTML (here from the Dojo Toolkit Editor2 widget)

When using a JavaScript WYSIWYG editor widget for text area content, the resulting HTML should be sanitized so no unallowed HTML tags (esp. script tags) are present. The [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) library handles HTML processing in the solution presented above, so you should place it in the Python path. The snippet also assumes that you have [the Dojo Toolkit](http://dojotoolkit.org/) and its Editor2 widget loaded on your page. **Note**: this snippet was originally written for use with Dojo Toolkit 0.4, and it hasn't been updated for 0.9 or 1.0.

  • forms
  • html
  • wysiwyg
  • dojo
  • security
  • sanitize
Read More

3110 snippets posted so far.