Login

Most bookmarked snippets

Snippet List

Date/time util template filters

**Explanations:** - the series "is_*_of" was created 'cos it's easier write: `{% if 10|is_day_of:date and user %}` than write: `{% ifequal date.day 10 %}{% if user %}...` - the series "inc/dec" is not complete, but can the extended to day, hour, minute, etc as you needs. It's util to inc 10 months since 05/31/2006 by example and get a 2007's date :) **Setup:** Insert the snippet into an_app/templatetags/datetimeutils.py. **Use in template:** `{% load datetimeutils %}` and use filters as following: - `{{ 30|is_day_of:a_date_time_variable }}` - `{{ 11|is_month_of:a_date_time_variable }}` - `{{ 2006|is_year_of:a_date_time_variable }}` - `{{ 58|is_minute_of:a_date_time_variable }}` - `{{ 23|is_hour_of:a_date_time_variable }}` - `{{ a_date_time_variable|dec_year:2 }}` - `{{ a_date_time_variable|dec_month:2 }}` - `{{ a_date_time_variable|inc_year:2 }}` - `{{ a_date_time_variable|inc_month:2 }}`

  • date
  • time
  • template-filters
Read More

xmlrpc basic auth

decorator which performs basic http auth authentication against the known userbase. This decorator is only for xml-rpc services. When there is no basic auth a proper response will be returned

  • auth
  • xmlrpc
Read More

Dynamic Models Revisited

Somebody mentioned in #django the other day that they have multiple databases with the same schema... Well *lucky me* so do I!! This is one way to work with this issue. I've also included migrate_table_structure just in case the schema doesn't exist in the new database yet. As per the multiple-db-support branch, write all of your databases into the OTHER_DATABASES in settings.py. You can now copy models from your various models.py files and use them in different databases at the same time. This can also be used to migrate databases from one dialect to the other without having to translate your data into an interim format (e.g. csv, XML). You can just do: qs = MyModel.objects.filter(**filters) NewModel = duplicate_model_and_rels(MyModel, 'new_db') #Assuming that the schema is already in new_db: for mod in qs: new = NewModel() new.__dict__ = mod.__dict__ new.save() I tried this using some hacks with SQLAlchemy, and the above approach is a huge amount quicker! I've used this to copy some stuff from an oracle db, into a sqlite db so i could carry on working later and transferred about 20,000 in 5 mins or so. GOTCHAS ======== This only works against my copy of multi-db as I've made a couple of changes. My copy is substantially the same as my patch attached to ticket 4747 though, so it might work to a point (especially the data migration aspect). If it doesn't work hit me up and I'll send you my patch against trunk. I'm not too crazy about the code in copy_field, it works fine, but looks ugly... If anyone knows of a better way to achieve the same, please let me know.

  • dynamic
  • multi-db
  • copy
Read More
Author: Ben
  • 2
  • 7

CSS Preprocessor

Here is a Django view that turns code like this: @variables { $varcolor: #333; } body { color: $varcolor; padding: 20px; } .space { padding: 10px; } .small { font-size: 10px; } #banana(.space, .small) { margin-bottom: 10px; } And turns it into something like this: body { color: #333; padding: 20px; } #banana { padding: 10px; font-size: 10px; margin-bottom: 10px; } .small { font-size: 10px; } .space { padding: 10px; } Notice the variables declaration at the top. The other feature is *extending* - here #banana extends .space and .small. The url.py entry might look something like this: (r'^css/(?P<css>(\w|-)+)\.css$','csspp.csspp'), Here referencing csspp.py in your path (root directory of your site probably). The code also looks for a CSS_DIR setting in your settings file. You will probably want to point straight to your media/css/ directory. **Known problems** * There is now way of extending selectors that are already extending something else. In the example code there is now way to extend #banana since it is already extending .small and .space.

  • css
  • preprocessor
  • csspp
Read More

simple string formatting filter

I use this filter quite a bit to keep my templates less cluttered. Instead of: {%if some_variable%}, {{some_variable}}{%endif%} I can write: {{some_variable|format:", %s"}} A common one I use is: {{some_variable|format:"<p>%s</p>"}}

  • filter
  • format
  • stringformat
Read More

duplicate model object merging script

Use this function to merge model objects (i.e. Users, Organizations, Polls, Etc.) and migrate all of the related fields from the alias objects the primary object. Usage: from django.contrib.auth.models import User primary_user = User.objects.get(email='[email protected]') duplicate_user = User.objects.get(email='[email protected]') merge_model_objects(primary_user, duplicate_user)

  • django
  • fields
  • model
  • generic
  • related
  • merge
  • duplicates
  • genericforeignkey
Read More

Markup Selection in Admin

This method lets you define your markup language and then processes your entries and puts the HTML output in another field on your database. I came from a content management system that worked like this and to me it makes sense. Your system doesn't have to process your entry every time it has to display it. You would just call the "*_html" field in your template. Requires: Django .96 [Markdown](http://cheeseshop.python.org/pypi/Markdown/1.6 "Python Package Index: Markdown") [Textile](http://cheeseshop.python.org/pypi/textile "Python Package Index: Textile")

  • admin
  • model
  • markup
  • markdown
  • textile
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

Slugify alternative

I prefer to use this slugification function rather than the one included with Django. It uses underscores instead of dashes for spaces, and allows dashes and periods to occur normally in the string. I decided on this when considering reasonable slugified titles such as... object-relational_mapper_2.5 ten_reasons_web-2.0_rocks django-trunk_0.99_updated

  • filter
  • slugs
  • slug
  • slugify
Read More

Subclassing a model.field for newforms

The newforms fields are more capable than the django models fields. In this snippet, we subclass models.IntegerField, and add min_value and max_value. e.g. age = MMIntegerField('How old are you?', min_value=13, max_value=120)

  • newforms
  • fields
  • model
Read More

Format transition middleware

Note: This is a testing middleware. This snippets may be changed frequently later. What's it ----------- Sometimes I thought thow to easy the output data into another format, except html format. One way, you can use decorator, just like: @render_template(template='xxx') def viewfunc(request,...): And the output data of viewfunc should be pure data. And if want to output json format, you should change the decorator to: @json_response def viewfunc(request,...): I think it's not difficult. But if we can make it easier? Of cause, using middleware. So you can see the code of `process_response`, it'll judge the response object first, if it's an instance of HttpResponse, then directly return it. If it's not, then get the format of requst, if it's `json` format, then use json_response() to render the result. How to setup `request.format`? In `process_request` you and see, if the `request.REQUEST` has a `format` (you can setup it in settings.py with FORMAT_STRING option), then the `request.format` will be set as it. If there is not a such key, then the default will be `json`. So in your view code, you can just return a python variable, this middleware will automatically render this python variable into json format data and return. For 0.2 it support xml-rpc. But it's very different from common implementation. For server url, you just need put the same url as the normal url, for example: http://localhost:8000/booklist/ajax_list/?format=xmlrpc Notice that the format is 'xmlrpc'. A text client program is: from xmlrpclib import ServerProxy server = ServerProxy("http://localhost:8000/booklist/ajax_list/?format=xmlrpc", verbose=True) print server.booklist({'name':'limodou'}) And the method 'booklist' of server is useless, because the url has include the really view function, so you can use any name after `server`. And for parameters of the method, you should use a dict, and this dict will automatically convert into request.POST item. For above example, `{'name':'limodou'}`, you can visit it via `request.POST['name']` . For `html` format, you can register a `format_processor` callable object in `request` object. And middleware will use this callable object if the format is `html`. Intall --------- Because the view function may return non-HttpResponse object, so this middleware should be installed at the end of MIDDLEWARE_CLASSES sections, so that the `process_response` of this middleware can be invoked at the first time before others middlewares. And I also think this mechanism can be extended later, for example support xml-rpc, template render later, etc, but I have not implemented them, just a thought. Options --------- FORMAT_STRING used for specify the key name of format variable pair in QUERY_STRING or POST data, if you don't set it in settings.py, default is 'format'. DEFAYLT_FORMAT used for default format, if you don't set it in settings.py, default is 'json'. Reference ----------- Snippets 8 [ajax protocol for data](http://www.djangosnippets.org/snippets/8/) for json_response

  • middleware
  • format
  • json
Read More

3110 snippets posted so far.