Login

All snippets written in Python

2956 snippets

Snippet List

HTTP (basic) auth enabled (new-style) syndication framework feed class

This snipped provides a subclass of the syndication Feed class that supports HTTP authentication (basic auth). Feeds that should support authentication can inherit from this class instead from the Feed class. It is basically the implementation of [Snippet #243](http://djangosnippets.org/snippets/243/) ported to the new-style syndication framework feeds (for which decorators don't work). Usage: class ArticleFeed(HTTPAuthFeed): def items(self, obj): return Article.objects.all().order_by('-created')[:10] def item_title(self, item): return item.title def item_description(self, item): return item.description

  • feed
  • rss
  • syndication
  • http-auth
  • basic-auth
  • atom
  • protected
Read More

Model merging function

Generic function to merge model instances. Useful when you need to merge duplicate models together, e.g. for users. Based on http://djangosnippets.org/snippets/382/, with several enhancements: * *Type checking*: only Model subclasses can be used and testing that all instances are of same model class * *Handles symmetrical many-to-may*: original snippet failed in that case * *Filling up blank attrs of original when duplicate has it filled* * *Prepared to use outside of command-line*

  • django
  • model
  • generic
  • related
  • merge
Read More

Resolve URLs to view name and args/kwargs

This is an expanded version of ["Resolve URLs to view name"](http://djangosnippets.org/snippets/1378/) without the monkey-patching. Simply pass in a URL such as '/events/rsvp/some_conference/' and you'll get back the view name or function (if name isn't available) and the arguments to it, eg 'events_rsvp', [], {'event_slug':'some_conference'}. Example (blatantly copied from previous snippet): === urlconf ==== urlpatterns = patterns('' (r'/some/url', 'app.views.view'), url(r'/some/other/(?P<url>\w+)', 'app.views.other.view', name='this_is_a_named_view'), url(r'/yet/another/(?P<url>\w+)/(\d+)', 'app.views.yetanother.view', name='one_with_args'), ) === example usage in interpreter === >>> from some.where import resolve_to_name >>> print resolve_to_name('/some/url') ('app.views.view',[],{}) >>> print resolve_to_name('/some/other/url') ('this_is_a_named_view',[],{'url':'url'}) >>> print resolve_to_name('/yet/another/url/5') ('one_with_args',[5],{'url':'url'}) From [fahhem.com](http://fahhem.com/) and [Recrec Labs](http://recreclabs.com/)

  • url
  • resolve
  • name
  • args
  • kwargs
Read More

Add CSS class template filter

Sometimes you want to add CSS classes to HTML elements that are generated by Django using their `__unicode__` representation, eg. you can output a form field with `{{ form.name }}`, but if you would like to add a certain CSS class to the outputted input or select tag you would have to assort to plain HTML. Using this filter you can simply do something like `{{ form.name|add_class:"span-4" }}` which will render an input like `<input type="..." name="..." class="span-4`.

  • django
  • template tag
  • css class
  • template filter
Read More

ModelMixin

Enables convenient adding of fields, methods and properties to Django models. Instead of: User.add_to_class('foo', models.CharField(...) User.add_to_class('bar', models.IntegerField(...) you can write: class UserMixin(ModelMixin): model = User foo = models.CharField(...) bar = models.IntegerField(...)

  • mixin
  • metaclass
  • util
  • metaprogramming
Read More

Error rate limiter

Prevents error flooding on high traffic production sites. Particularly useful to prevent clogging email servers etc. See [discussion](http://groups.google.com/group/django-developers/browse_thread/thread/1dabc9139dd750ca/1d86fdca23189a7d?lnk=gst&q=error#1d86fdca23189a7d) and [closed ticket](http://code.djangoproject.com/ticket/11565). Uses memcache if it can, or falls back to local, in-process memory where unavailable (down, etc). Tweak to your needs using setting ERROR_RATE_LIMIT (seconds). Requires Django 1.3+ or trunk r13981+

  • error
  • logging
  • emails
Read More
Author: s29
  • 2
  • 3

Modify requests in your unit tests (improvement on RequestFactory)

This is an update to Simon Willison's snippet http://djangosnippets.org/snippets/963/, along with one of the comments in that snippet. This class lets you create a Request object that's gone through all the middleware. Suitable for unit testing when you need to modify something on the request directly, or pass in a mock object. (note: see http://labix.org/mocker for details on how to mock requests for testing) Example on how to use: from django.test import TestCase from yourapp import your_view from yourutils import RequestFactory class YourTestClass(TestCase): def setUp(self): pass def tearDown(self): pass # Create your own request, which you can modify, instead of using self.client. def test_your_view(self): # Create your request object rf = RequestFactory() request = rf.get('/your-url-here/') # ... modify the request to your liking ... response = your_view(request) self.assertEqual(response.status_code, 200) Suggestions/improvements are welcome. :)

  • testing
  • request
  • client
  • testcase
Read More

Simple Mobile Support

For those interested in making a mobile site geared toward the higher end devices, and wanting a little leverage over device-specific quirks. These are the big players in the U.S. market, but of course, add your own User-Agents to match your audience's popular browsers. Usage: <html class="{{ device.classes }}"> You can also leverage template logic: {% if device.iphone %} <p>You are browsing on {% if device.iphone = "iphone4" %} iPhone 4 {% else %} an iPhone pre-version 4{% endif %} </p> {% endif %}

  • mobile
  • context_processors
Read More

X-Sendfile static file serve view

This view has the same functionality as Django's builtin static view function but when the configuration option `USE_XSENDFILE = True` is specified in the settings it returns the absolute path of the file instead of its contents. This allows the mod_xsendfile module in Apache or Lighttpd to take care of efficiently serving the file while still allowing for Django to take care of other processing of the request, like access control or counting the amount of downloads.

  • static
  • xsendfile
Read More

Export Django data to datestamped tarball -- choose individual models for handy packaging and archiving

Just like it says -- set it up and run. Use it for server migrations, for project handoffs, in cron jobs, you name it. I have never had problems exporting models to individual fixtures in this way, and only one bout of trouble re-importing them (and that was, like, an impossible-triangle of OneToOneField dependencies anyway, and they were going from a sqlite file to a postgres schema that totally had inappropriate nullable columns in it). I find that the json files named for what they contain is helpful when and if manage.py does freak out during an import, as the output from `loaddata` command is so opaque it's autistic, basically. A trivial refactoring effort could make it into a management command -- it already makes use of the builtin `dumpdata` command class internally. However I did not feel like overthinking it enough to set it up in a repository (doubtlessly padded with unrelated 'utilities' and explanatory .rst files) and then writing a blog post to sell it to you. That is why you are reading this code here, instead of on GitHub. Don't get me wrong, GitHub is awesome, and like a consummate host... but not the way I love me some quick and dirty snippet code, these days. Whatever, you say lazy, I say productively relaxed, potato/potahto. Erm. In any case please do enjoy this model fixture-exporter. Yes.

  • django
  • python
  • json
  • export
  • data
  • script
  • command
  • archive
  • django1.1
  • backup
  • datestamp
  • tar
  • tarball
Read More

RSS feed with content:encoded elements

This creates an RSS feed that has "content:encoded" elements for each item in the feed. The "description" is best used for a brief summary of the entry, while the extra ["content:encoded"](http://purl.org/rss/1.0/modules/content#syntax2) element is designed for the entire contents of something. This is the code I'm using for a weblog app. The main features you'd need to copy to add "content:encoded" elements to your own feed are: * **ExtendedRSSFeed()** -- this is used to create a new kind of feed generator class that will know about these extra elements. * **feed_type = ExtendedRSSFeed** -- we tell the feed class which feed generator class to use. * **item_extra_kwargs()** -- we add the "content:encoded" element to each item. This populates the element by calling... * **item_content_encoded()** -- this prepares the actual content. The name doesn't have to be in this format, but it seemed sensible to follow convention. The body of my weblog Entries are split into two parts and here it makes sure we add both parts, both of which contain HTML (which the syndication classes will encode appropriately.

  • feed
  • rss
  • content
  • syndication
  • feeds
Read More