Login

Most bookmarked snippets

Snippet List

Readonly admin fields

Put this code and import it where you define your ModelAdmin-classes. # typical admin.py file: from django.contrib import admin from foo.bar import ReadOnlyAdminFields class MyModelAdmin(ReadOnlyAdminFields, admin.ModelAdmin): readonly = ('field1', 'field2',)

  • django
  • admin
  • field
  • readonly
Read More

Google Contacts API friend finder

This view will provide a link for AuthSub proxy authentication to the Google Contacts API and then grab the user's Google contacts and compare against User.email for possible user relationships. A couple of things to note: * Dependency on the GData Python client library: http://code.google.com/p/gdata-python-client/ * The domain hosting the view must be verified by Google's domain manager (otherwise API calls will result in a 403): https://www.google.com/accounts/ManageDomains Thanks to Simon for get_url_host and get_full_url.

  • api
  • gmail
  • google
  • gdata
  • contacts
Read More

Generate newforms-admin admin.py file

This is a utility script that scans a models.py file and automatically outputs the corresponding newforms-admin source code - the code that goes into the admin.py file. The purpose is to simplify the migration to newforms-admin. Here is what it outputs: * an import line that lists only the needed classes from the model. * inline editing classes - inheriting from either `admin.TabularInline` or `admin.StackedInline` * admin options classes containing any original `Admin` class contents (`'fields'` is replaced by `'fieldsets'` and the value of `'classes'` is made into a tuple), plus the following fields whose values are determined automatically: `inlines`, `prepopulated_fields`, `filter_horizontal`, `filter_vertical` and `raw_id_fields` * invokations of `admin.site.register` for the generated admin options classes. Example usage of the script (this will generate the admin.py file for the models.py file in the satchmo.product module): >./new-forms-gen.py satchmo.product > admin.py

  • newforms-admin
Read More
Author: NL
  • 16
  • 21

Capture template output as a variable

Tags like `url` and `trans` provide no way to get the result as a context variable. But how would you get a computed URL into a `blocktrans`? This snippet solves the general problem. Just put the template code whose output you want to capture within `captureas` tags. For example: {% captureas login_url %}{% url login %}{% endcaptureas %} {% blocktrans %} <a href="{{login_url}}">login</a> {%endblocktrans%}

  • template
  • variable
  • assign
  • capture
  • blocktrans
Read More

typygmentdown

Based heavily on [snippet #119](/snippets/119/), this is an all-in-one function which applies Markdown and typogrify, and adds Pygments highlighting (selected from a class name or by having Pygments guess the language) to any `<code>` elements found in the text. It also adds some niceties for picking up useful arguments to Markdown and Pygments, and registers itself as a markup filter with the `template_utils` formatter. Requirements: * [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) * [Pygments](http://pygments.org/) * [python-markdown](http://www.freewisdom.org/projects/python-markdown/) * [template_utils](http://code.google.com/p/django-template-utils/) * [typogrify](http://code.google.com/p/typogrify/)

  • pygments
  • markup
  • markdown
  • typogrify
Read More

Querying on existence of a relationship

When you have two models joined by a foreign key, it's common to want to retrieve a set of objects from the "target" of the foreign key based on whether there are any objects "pointing" to them. This snippet demonstrates how to do so, using the `extra` method of the default model manager. Note that this is probably more efficient than using two ORM methods (e.g., selecting all values from one table, and using an `id__in` lookup on the other) since it does the whole thing in one query and avoids instantiating any intermediate objects.

  • models
  • orm
  • foreign-keys
Read More

Ordered items in the database - alternative

Every now and then you need to have items in your database which have a specific order. As SQL does not save rows in any order, you need to take care about this for yourself. No - actually, you don't need to anymore. You can just use this file - it is designed as kind-of plug-in for the Django ORM. 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). Usage example: Add this to your `models.py` from positional import PositionalSortMixIn class MyModel(PositionalSortMixIn, models.Model): name = models.CharField(maxlength=200, unique=True) Now you need to create the database tables: `PositionalSortMixIn` will automatically add a `postition` field to your model. In your views you can use it simply with `MyModel.objects.all().order_by('position')` and you get the objects sorted by their position. Of course you can move the objects down and up, by using `move_up()`, `move_down()` etc. In case you feel you have seen this code somewhere - right, this snippet is a modified version of [snippet #245](/snippets/245/) which I made earlier. It is basically the same code but uses another approach to display the data in an ordered way. Instead of overriding the `Manager` it adds the `position` field to `Meta.ordering`. Of course, all of this is done automatically, you only need to use `YourItem.objects.all()` to get the items in an ordered way. Update: Now you can call your custom managers `object` as long as the default manager (the one that is defined first) still returns all objects. This Mix-in absolutely needs to be able to access all elements saved. In case you find any errors just write a comment, updated versions are published here from time to time as new bugs are found and fixed.

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

Making templatetags global to all templates

I found myself putting `{%load ... %}` in every template that I was writing, so DRY .. I created an app called 'globaltags' and in its `__init__.py`, I just pre-load the tags that I use frequently. The [pyif](http://www.djangosnippets.org/snippets/130/) and [expr](http://www.djangosnippets.org/snippets/9/) tags are excellent tags, and I highly recommend them for getting the most out of django's template language. The [dbinfo](http://www.djangosnippets.org/snippets/159/) snippet is something that I came up with to easily output SQL debugging information.

  • tag
Read More

Generic markup converter

I'm a big fan of Markdown, and often set up models to automatically apply it to certain fields before saving. But that's not really flexible, because if I then distribute the code someone else might want to use reStructuredText or Textile or whatever, and then they have to hack my code. So here's a function which looks for a setting called `MARKUP_FILTER` and, based on what it finds there (see the docstring for what it looks at), chooses a text-to-HTML conversion function and applies it to a piece of text. Since Textile, Markdown and reStructuredText all support various useful options, it has the ability to pick up arbitrary keyword arguments and pass them through.

  • markup
  • markdown
  • textile
  • restructuredtext
Read More

Keep settings.py in version control safely

Here is a trivial way to keep your Django project in shared version control or in a public repository without exposing settings that could have security implications, and without needing to modify settings.py for your local test or production environments on checkout. This is also a way to separate development settings from production settings, or to deploy the same code on multiple servers while only changing one site-specific "dotfile."

  • files
  • configuration
  • settings
  • development
  • debug
Read More

Facebook Authentication Backend

Authentication through Facebook's Graph API. See [http://developers.facebook.com/docs/authentication/](http://developers.facebook.com/docs/authentication/) [http://developers.facebook.com/docs/authentication/permissions](http://developers.facebook.com/docs/authentication/permissions) [http://developers.facebook.com/docs/api](http://developers.facebook.com/docs/api) [http://github.com/facebook/python-sdk/blob/master/examples/oauth/facebookoauth.py](http://github.com/facebook/python-sdk/blob/master/examples/oauth/facebookoauth.py) Define the facebook tokens in settings.py and replace <app_name> with the name of your app. You will probably want to modify the scope on the authorize link in the template, see the authentication permissions link. This updates the user model every time the user logs in but I think that it is okay so the data is always correct. I have tested this but not rigorously. If there is a hole and everyone gets admin rights to your site don't say I didn't warn you :). Comments are appreciated. 16 June 2010 Added missing imports. Cleaned up the template. Shouts out to @obeattie and @whalesalad

  • graph
  • authentication
  • login
  • auth
  • facebook
  • oauth
Read More

reCAPTCHA integration

Integrating [reCAPTCHA](http://recaptcha.net/) with Django. **Warning**: although *remoteip* is used as optional parameter in this snippet, it is likely to become mandatory in the future. Please see [the comment by Jim Garrison](http://www.marcofucci.com/tumblelog/26/jul/2009/integrating-recaptcha-with-django/#comment-262) for more detail. Generic version of [this snippet](http://www.djangosnippets.org/snippets/433/). 1. Register on [reCAPTCHA](http://recaptcha.net/) to get your public/private key pair 2. Add your keys in settings.py 3. Add [recaptcha-client](http://pypi.python.org/pypi/recaptcha-client) to your project 4. Put ReCaptchaField and ReCaptcha widget somewhere (I've used a generic app `marcofucci_utils`) 5. Configure your form More information on my website [marcofucci.com](http://www.marcofucci.com/tumblelog/26/jul/2009/integrating-recaptcha-with-django/).

  • captcha
  • recaptcha
Read More

Accepting and processing PayPal IPN messages (including using App Engine)

PayPal's [https://www.paypal.com/ipn](IPN mechanism) is ridiculously easy to consume. You can tell PayPal to POST every single transaction on your account to a URL somewhere, then set up a handler at that URL which processes those transactions in some way. Security is ensured by POSTing the incoming data back to PayPal for confirmation that the transaction is legitimate. These classes are probably over-engineered, but they were a fun experiment in creating class-based generic views.

  • appengine
  • paypal
  • payment
  • ipn
Read More

3110 snippets posted so far.