Login

Most bookmarked snippets

Snippet List

Template filters utils

**Explanation:** That template filters is util for combine boolean-return conditions using template tag `{% if %}`. **Setup:** Insert the snippet into an_app/templatetags/myutils.py. **Use in template:** {% load myutils %} and use filters as following: - `{% if 10|is_multiple_of:5 %}` - `{% if 10|in_list:a_list_variable %}` - `{% if user.username|is_equal:a_variable %}` - `{% if user.username|is_not_equal:a_variable %}` - `{% if a_variable_|is_lt:5 %}` - `{% if a_variable_|is_lte:5 %}` - `{% if a_variable_|is_gt:5 %}` - `{% if a_variable_|is_gte:5 %}`

  • template-filters
Read More

multiple model form with image

You have two models, one of which also has an image field. You want to get the data into a form and edit it. This also requires showing the url of the image, if there is one, on the form. This is a complete working example. No big deal, but for newbies, a complete working example could be valuable.

  • newforms
  • imagefield
Read More

"Link To" helper tag

Simple template tag that assumes some common conventions in order to quickly get a link to a specific model instance.

  • template
  • models
  • links
  • tags
  • anchors
Read More

AMF Message passing through Middleware

Middleware for communicating with Flash Player via Flashticle and Django. Setup a view at /gateway/math/multiply like so: def multiply(request, m1, m2): return m1 * m2 Then in your Flex/Flash app you call "math.multiply" on a NetConnection pointing to http://domain.com/gateway/ Does not yet support authentication.

  • flash
  • amf
  • flashticle
Read More

Incrementally Return CSV

The first function (ftype_batch) is a view that passes the first part of the CSV filename and a queryset intended to write out to the file. run_batch prepares the HttpResponse for incrementally writing, and write_batch actually writes out the data. The logic in write_batch is custom to what I need done, but as long as the csv writer receives a sequence to write, it should work.

  • csv
  • incremental
Read More

Email on new comments

I know ubernostrum has the nice comment_utils, but I need something that would notify the owner of the comment's content object (where the model has a foreignkey field to django.contrib.auth.models.User), but I didn't need all the moderation stuff. I stuck this in my models.py, where YOURMODEL is the name of the model object with comments attached, and a user field.

  • email
  • comments
Read More

Using descriptors for lazy attribute caching

Python's [descriptor][1] protocol can seem a bit esoteric at first; however, it can be invaluable in handling everyday idioms and patterns - something that the Django framework authors have taken advantage of in numerous occasions (e.g.: [auth middleware][2]). One such idiom I see and use often and would like to generalize is the attribute-existence check-or-set routine illustrated here: def get_foo(self): if not hasattr(self, '_foo'): self._foo = init_foo() return self._foo Rather than coding this up multiple times (either for a given class or across many unrelated classes), I would prefer to delegate this repetitive work to a descriptor and remain [DRY][3]. The means to this end is implemented as a variation on the Python `property` construct, and is intentionally over simplistic (I leave the details of the heavy lifting up to the reader). The basic premise shown in source here is simply straight-forward Python, a quick and dirty example of how it could be utilized within a Django context is shown here: from django.db import models from cacheprop import CacheProperty2 ARTIFACT_TYPES = ( ('F', _('File')), ('D', _('Directory')), ('A', _('Alias')), ) class Artifact(models.Model): # model fields name = models.CharField(maxlength=64) type = models.CharField(maxlength=1, choices=ARTIFACT_TYPES) file_metadata = CacheProperty2( lambda self: self.filemetadata_set.get(artifact__id=self.id) ) class FileMetadata(models.Model): byte_size = models.IntegerField() artifact = models.ForeignKey(Artifact, unique=True) [1]: http://users.rcn.com/python/download/Descriptor.htm [2]: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/middleware.py [3]: http://c2.com/cgi/wiki?DontRepeatYourself

  • python
  • descriptors
Read More

SAS70 Compliant Password Validator

Validator to verify a password is SAS70 compliant: greater than or equal to eight characters, and contains at least three out of the four characters( Uppercase, Lowercase, Number, Special Character ).

  • validator
Read More

XhtmlDegraderMiddleware

The XhtmlDegraderMiddleware class is designed to make it easier to deploy XHTML contents onto the World Wide Web. The correct MIME media type for sending XHTML is `application/xhtml+xml` -- the `text/html` media type is also acceptable provided [certain guidelines](http://www.w3.org/TR/2002/REC-xhtml1-20020801/#guidelines) are followed. The vast majority of web browsers released from 2002 onwards have good XHTML support; this includes Mozilla Firefox, Opera, and Apple Safari. Two notable exceptions are Internet Explorer 7.0 and Netscape Navigator 4.8; instead of displaying XHTML, they present the user with a download dialog instead. The role of the XHTML Degrader, then, is to automatically detect when browsers do not support XHTML, and to degrade the contents into something they're capable of rendering. **How it works** XhtmlDegraderMiddleware checks the content type of all HTTP responses. If the XHTML media type is set, the `Accept` request header is examined to determine whether the user agent actually supports XHTML. If so, the contents is sent unaltered. If not, a number of silent changes are made to make the response more friendly to XHTML-challenged browsers and web crawlers. Firstly, the `Content-Type` header is set to the HTML media type. Any XML processing instructions are removed, and a `DOCTYPE` is added if none is present. In the case of Internet Explorer, this should ensure the content is rendered in "standards compliance" mode. Empty elements are made to have a space before their trailing slash. N.B. If an HTTP response is already set to `text/html`, or set to any media type other than `application/xhtml+xml`, the middleware will have no effect. Note also that if you use GZipMiddleware, you should ensure that it appears in your MIDDLEWARE_CLASSES setting before XhtmlDegraderMiddleware, to allow the XHTML Degrader to act first.

  • middleware
  • xhtml
Read More
Author: dmh
  • 4
  • 4

Automatic Paragraphs

I just converted the autop filter from Drupal (which is itself based on a Wordpress filter) from PHP to Python. I had to change the format of the regular expressions a bit and make them raw strings, but otherwise the function is unchanged. It should work exactly like the original function.

  • filter
  • text
  • format
Read More

Additional Change List Columns

Ever wanted to add a link or two at the end of a row in a model's change list? Say you had a model for people and a model for registrations or blog posts and you want to modify the people change list so it has a link to, say all of the registrations or blog posts for the person. Well, Django provides half of the solution already in that the example registration change_list already handles the display of all registrations tied to that person. For example, the url `/admin/registrations/registration/?person__id__exact=121` gets you to a filtered list of registrations for the person with the id of 121. This is the same url used if you use list_filter in your model definition (though setting list_filter is not required for what we're doing). Okay, so to add a link to the end of each person row in the change list, you need to create a template tag similar to "person_result_list" in the code. There, I've given an example that adds two links. Each dictionary in additional_links needs to have at least a text, sortable, and url_template attribute. The text attribute is what will display as the header to the column. url_template will be fed the id of the row object (in this example, a person id), which you can use to construct the link for each row. You could extend this if you wish, though all I ever need is the id. And the last step is to use your new template tag in a modified change_list.html in place of the default result_list tag. The example at the bottom of the code shows an example usage of the tag. Hope this makes sense and is helpful to someone!

  • template
  • admin
  • tags
  • change_list
Read More

If in list template tag

Given an item and a list, check if the item is in the list ----- item = 'a' list = [1, 'b', 'a', 4] ----- {% ifinlist item list %} Yup, it's in the list {% else %} Nope, it's not in the list {% endifinlist %}

  • template
  • tag
  • list
  • in
Read More

Random Quotes

Display a random quote. Just add some quotes to the app (you may want to add the administration interface options) and then load the template tag: `{% load random_quote %}` and then call the tag to display a random quote from the app `{% random_quote %}` feel free to improve it/whatever.. :)

  • templatetag
  • random
  • quotes
Read More

3110 snippets posted so far.