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`.
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(...)
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+
It gets the thumbnail picture url from a youtube video url.
Example
<img src="{{vide.url|youthumbnail:'s'}}"/>
It supports 2 sizes small(s) and large (l)
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. :)
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 %}
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.
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.
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.
The template creation script referenced [here] (http://docs.djangoproject.com/en/dev/ref/contrib/gis/install/#ubuntudebian) doesn't work on Ubuntu Lucid, where the default PostgreSQL version is now 8.4 and some things have been moved around. I've edited the script to work on Ubuntu Lucid.
This code is taken from a [Stack Overflow answer by Will Hardy](http://stackoverflow.com/questions/3715550/creating-a-list-on-the-fly-in-a-django-template/3715794#3715794).
Usage: `{% collect var1 var2 'foo' 'bar' 5 as some_list %}`.
Sometimes one wishes to create a list on the fly within a template. Perhaps a collection needs to be passed to a template filter, but the collection cannot be created in the view since the values of one or more of its items are set in the template.
A contrived example:
{% with 5 as max %}{% with posts|length as len %}
{% for post in posts %}
{% if forloop.counter <= max %}
{% include 'excerpt.dhtml' %}
{% endif %}
{% endfor %}
{% collect len max as limits %}
<p>Displaying {{ limits|minimum }} of {{ len }} post{{ posts|pluralize }}.</p>
{% endwith %}{% endwith %}
The final line will state how many posts are displayed: something like "5 of 24" or "2 of 2".
This particular problem can be solved in a number of other ways, some of which are more appropriate. Having a template tag that can create lists on the fly is potentially useful in quite a few situations, though.
I don't know whether this need is common enough to warrant being in the core. If something like this is to be included one day, it'd be much nicer to overload the `with` tag than to introduce a new tag. `{% with var1 var2 var3 as some_list %}` reads well.
Splitting the information about a user across two models (User and UserProfile) is not to everyone's liking. This snippet monkeypatches the User model so that users can access transparently their profile information while still storing the data in two tables under the hood. Thus it is similar to the inheritance approach (http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/) but has the benefit of (a) not requiring a custom authentication backend or middleware and (b) loading the profile instance lazily, so there's no extra overhead if the profile infromation is not accessed. Read the docstrings for more details.
You're looking at the top-rated snippets currently on the site; if you'd like to contribute, sign up for an account and you'll be able to rate any snippet you see.