Login

Most bookmarked snippets

Snippet List

Globs for INTERNAL_IPS

Allows you to include globs of IP addresses in your INTERNAL_IPS. It's shell-style glob syntax (the [fnmatch module](http://docs.python.org/library/fnmatch.html)). This should be helpful with the [Debug Toolbar](http://github.com/robhudson/django-debug-toolbar/tree/master), among other things. Like [#1362](http://www.djangosnippets.org/snippets/1362/), but with no external dependencies.

  • settings
  • debug
  • ip-addresses
  • internal-ips
Read More

Include entire networks in INTERNAL_IPS setting

A simple addition to the settings.py file of your project to allow you to easily specify entire network ranges as internal. This is especially useful in conjunction with other tools such as the [Django Debug Toolbar](http://github.com/robhudson/django-debug-toolbar/tree/master). After you set this up, the following test should pass test_str = """ >>> '192.168.1.5' in INTERNAL_IPS True >>> '192.168.3.5' in INTERNAL_IPS FALSE """ Requirements ------------ * The [IPy module](http://software.inl.fr/trac/wiki/IPy) Acknowledgements ---------------- Jeremy Dunck: The initial code for this idea is by Jeremy and in [Django ticket #3237](http://code.djangoproject.com/ticket/3237). I just changed the module and altered the use of the list superclass slightly. I mainly wanted to put the code here for safe keeping. Thanks Jeremy!

  • settings
  • ip-addresses
  • cidr
  • internal-ips
Read More

Template range filter

Easy to use range filter. Just in case you have to use a "clean" for loop in the template. Inspired by [Template range tag](http://www.djangosnippets.org/snippets/779/) Copy the file to your templatetags and load them. [Django doc | Custom template tags and filters](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/)

  • template
  • filter
  • range
Read More

themed_template_loader

I developed this template loader for adding themes support in [gitology](http://www.amitu.com/gitology/). In order to support theming django applications, add this template loader at as the first TEMPLATE_LOADERS settings.py setting. Anywhere you request base.html, blog/index.html, when the theme is set to "bw", it will look for bw/base.html or bw/blog/index.html files first. Takes care of both render_to_response() in view or {% load template %} in templates.

  • templateloader
  • theming
Read More

Base class for RESTful Views

Subclass `Resource` to create a view that will dispatch based on the HTTP method of the request. class View(Request): def DELETE(self, request): ... def GET(self, request): ... def PUT(self, request): ... Other snippets provided inspiration: * [436](http://www.djangosnippets.org/snippets/436/) * [437](http://www.djangosnippets.org/snippets/437/) * [1071](http://www.djangosnippets.org/snippets/1071/) * [1072](http://www.djangosnippets.org/snippets/1072/) The code is also available on [GitHub](http://github.com/jpwatts/django-restviews/).

  • views
  • rest
  • http
  • view
Read More

GoogleAdmin: GMaps base layer in Geographic Admin (GeoDjango)

This GeoDjango subclass substitutes in the Google Maps base layer instead of the default one provided by Open Street Map. Requires the [google.html](http://www.djangosnippets.org/snippets/1145/) and [google.js](http://www.djangosnippets.org/snippets/1146/) templates (must be placed in `gis/admin` somewhere in your template path). Requires a Google Maps API key -- please abide by Google's [terms of service](http://code.google.com/apis/maps/terms.html).

  • gis
  • google
  • map
  • gmaps
  • layer
  • openlayers
Read More

ajax_validator generic view

Sample jQuery javascript to use this view: $(function(){ $("#id_username, #id_password, #id_password2, #id_email").blur(function(){ var url = "/ajax/validate-registration-form/?field=" + this.name; var field = this.name; $.ajax({ url: url, data: $("#registration_form").serialize(), type: "post", dataType: "json", success: function (response){ if(response.valid) { $("#"+field+"_errors").html("Sounds good"); } else { $("#"+field+"_errors").html(response.errors); } } }); }); }); For each field you will have to put a div/span with id like fieldname_errors where the error message will be shown.

  • ajax
  • javascript
  • view
  • generic
  • jquery
  • validation
  • form
Read More

change SITE_ID on fly

Django SITE_ID is a global setting, so the site framework requires you to run multiple instances of Django; at least one for each site. But i want have one instance for multiple sites. This snippet solve this task by change SITE_ID on fly. /sorry my bad english/

  • settings
  • site_id
  • site-contrib
Read More

Alternative to Captchas (Without Human Interaction)

This security field is based on the perception that spambots post data to forms in very short or very long regular intervals of time, where it takes reasonable time to fill in a form and to submit it for human beings. Instead of captcha images or Ajax-based security interaction, the SecurityField checks the time of rendering the form, and the time when it was submitted. If the interval is within the specific range (for example, from 5 seconds till 1 hour), then the submitter is considered as a human being. Otherwise the form doesn't validate. Usage example: class TestForm(forms.Form): prevent_spam = SecurityField() # ... other fields ... The concept works only for unbounded forms.

  • captcha
  • security
  • form
  • field
  • antispam
  • antibot
Read More

Frequently used tags/filters for Jinja2

Some frequently used filters and global functions: **url** - same as django url tag **nbspize** - replace all spaces with nbsp **get_lang** - get current language code **timesince** - converted django timesince tag **timeuntil** - converted django timeuntil tag **truncate** - tag that truncates text call it with an str argument like '20c' or '5w', where the number provides the count and c stands for charachters and w stands for words

  • tags
  • jinja
  • jinja2
Read More

TestSettingsManager: temporarily change settings for tests

This TestSettingsManager class takes some of the pain out of making temporary changes to settings for the purposes of a unittest or doctest. It will keep track of the original settings and let you easily revert them back when you're done. It also handles re-syncing the DB if you modify INSTALLED_APPS, which is especially handy if you have some test-only models in tests/models.py. This makes it easy to dynamically get those models synced to the DB before running your tests. Sample doctest usage, for testing an app called "app_under_test," that has a tests/ sub-module containing a urls.py for testing URLs, a models.py with some testing models, and a templates/ directory with test templates: >>> from test_utils import TestManager; mgr = TestManager() >>> import os >>> mgr.set(INSTALLED_APPS=('django.contrib.contenttypes', ... 'django.contrib.sessions', ... 'django.contrib.auth', ... 'app_under_test', ... 'app_under_test.tests'), ... ROOT_URLCONF='app_under_test.tests.urls', ... TEMPLATE_DIRS=(os.path.join(os.path.dirname(__file__), ... 'templates'),)) ...do your doctests... >>> mgr.revert()

  • settings
  • test
  • syncdb
Read More

Django and jQuery -- pulling info from a long-running process

Another sample of how to integrate Django and jQuery. === This starts a function in views.py that takes a long time to finish. It sets a session variable so that another function can report on the situation. We use jquery and ajax to 'pull' that data from Django so as to provide a progress report. I don't yet know how to background a long-running process, but this is an okay stop-gap method to use. I hope. \d

  • ajax
  • json
  • jquery
  • data
  • progress
  • pull
Read More

Update All Apps to Latest Revision

This snippet is based on [#844](http://www.djangosnippets.org/snippets/844/ "#844") and [#892](http://www.djangosnippets.org/snippets/892/ "#892") and updates all apps in the current directory using hg, svn, git or bzr. Including subdirectories not under version control (subfolders to keep your stuff organized). For example: python/lib/ django-trunk/ django-0.96/ pydelicious/ (...) django-apps/ django-tagging/ django-pagination/ django-registration/ django-threadedcomments/ django-mptt/ (...) The script will iterate through all of your apps (in the current dir and also recursively in subdirs NOT under version control) and update them to the latest version. To run, simply execute: python update_apps.py in the desired parent folder. Just in case it could be useful: In my case I'm using MAC OS X. I have a folder full of miscellaneous scripts under my HOMEDIR, with this content: /Users/Dedaluz/bin/update_apps.py /Users/Dedaluz/bin/update_apps (this is a bash script) The update_apps script contains simply: #!/bin/bash python /Users/Dedaluz/bin/update_apps.py Then I put this folder in my path, so in my /HOMEDIR/.bash_profile I add this line export PATH=$PATH:$HOME/bin And I just can update from any parent folder just going there and typing: update_apps

  • script
  • update
  • svn
  • git
  • hg
  • bzr
Read More

i18n base model for translatable content

Together with my mentor, Dusty Phillips, I have developed a simple class that dynamically adds two fields to its subclasses. This is useful in cases when a single piece of content is divided into translatable and non-translatable fields, connected by a 1-to-many relationship. ## Update 2009/03/30 Since its inception, this snippet has grown into a significantly more powerful solution for translatable content (I use it myself with great joy :). The project is now hosted on github: [project page](http://github.com/foxbunny/django-i18n-model/tree/master) ## Update 2008/07/09 It is now possible to define `i18n_common_model` attribute in `class Meta` section. Here's an example: class Meta: i18n_common_model = "MyCommonModel" As you can see, it has to be a string, not the real class, and it is case-sensitive. ## Example class Article(models.Model): author = models.CharField(max_length = 40) class Admin: pass class ArticleI18N(I18NModel): title = models.CharField(max_length = 120) body = models.TextField() class Admin: pass # optionally, you can specify the base class # if it doesn't follow the naming convention: # # class Meta: # i18m_common_model = "Article" When the ArticleI18N class is created, it automatically gains two new fields. `lang` field is a CharField with choices limited to either `settings.LANGUAGES` or `django.conf.global_settings.LANGUAGES`. The other field is `i18n_common` field which is a ForeignKey to Article model. ## The conventions * call the translation model `SomeBaseModelI18N`, and the non-translation model SomeBaseModel (i.e., the translation model is called basename+"I18N") * the first convention can be overriden by specifying the base model name using the `i18n_common_model` attribute in `Meta` section of the `I18N` model * I18N model is a subclass of `I18NModel` class ## Original blog post [http://blog.papa-studio.com/2008/07/04/metaclasses-and-translations/](http://blog.papa-studio.com/2008/07/04/metaclasses-and-translations/)

  • models
  • i18n
  • metaclass
  • translated-content
Read More

3110 snippets posted so far.