Login

All snippets

Snippet List

Encryption Fields

This provides some basic cryptographic fields using pyCrypto. All encryption/decription is done transparently and defaults to use AES. Example usage: class DefferredJunk(models.Model): semi_secret = EncryptedCharField(max_length=255)

  • model
  • field
  • encryption
Read More

List all Form Errors

You can place this code above your form and it will list out all errors in your form if there are errors. Sometimes I like listing the errors at the top of the form because I think it looks cleaner. Make sure you add error_messages={'required': 'My detailed error here'} in your view.py for your form.

  • error
  • form
Read More

simple email validation function

This very basic function I was missing in this part of the Django Documentation when creating a custom MultiEmailField: http://docs.djangoproject.com/en/dev/ref/forms/validation/

  • email
  • validation
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

Multi-level (tree-ish) navigation

An old snippet I made in my first django project. Nowadays I code menus in HTML and just use the perms proxy: https://docs.djangoproject.com/en/1.0/topics/auth/#id6 Credits, (awsome persons that helped me getting it to work efficiently and for free): * Yhg1s and waveform from #python@freenode * zendak from #django@freenode Thank you!

  • menu
  • navigation
  • menubar
  • navbar
Read More

Dynamic Backends

This allows various implementations of a common interface to be loaded. Back end modules can be specified in settings.py, and from there be loaded and treated polymorphically by an application.

  • backend
  • dynamic-factory
Read More

Mod to allow simple_tag to access context

This is a mod I made to the Django simple_tag system to let the simple_tags access comments. I plan to try and get it integrated into the trunk, so it's mainly here so (a) the people on django-developers can see it, and (b) while I'm waiting, or if it doesn't get put in the trunk, people can use it. **Installing** 1. Open the module `django.template.__init__`, wherever that lives. 2. Scroll down to the beginning of " `class Library:` " 3. Find the simple_tag function (" `def simple_tag(self,func):` ") 4. Replace the function (even the whitespace before each line) with the code snippet. **Usage** 1. When defining a simple tag (see the [docs](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#shortcut-for-simple-tags) for more info), have the first parameter in your function be named "`context`". Otherwise, an error will be thrown. It can accept other parameters like normal. 2. Use `register.simple_tag(my_function_name, takes_context=True)` to register your function as one that will use the context. 3. The tag's function can access the context like a dictionary - to get a value, just use `context['cheese']`, or to set one, use `context['cheese'] = 'Limberger'`. Due to the context's mutability, this will affect the context in the main template as well. **Notes** This code hasn't been tested in a "production environment", but I did test my modifications thoroughly, and if you don't add `takes_context=True`, `simple_tag` will behave exactly as normal. Of course, if there is a problem, make sure you leave a comment. **Code** Since most of the code is hacked up from other Django library functions, and to prepare for if and when it's merged into the trunk, it's released under the BSD license.

  • template
  • template-tags
  • template-engine
Read More

Photologue wiki-syntax templatetag

**updated 12/16/08** I run several blogs by visual-artists and web-designers who want a quick way to insert images into their blog without the awkwardness of WSYIWYG and without the technicality of code (eww...). Thanks in advance for your input. #Syntax in a blog goes: [[thumb:the-image-slug]] # Gives you a thumbnail [[image:the-image-slug]] # Presents full-size-image Then of course: {% blog.post|yeagowiki %} You will also need to create some templates (see snippet). Here's a sample: <!-- /templates/photologue/image_snippet.html --> <div class="photologue-image"> <a href="{% if url %}{{ url }}{% else %}/media/{{ image.image }}{% endif %}"> <img src="{{ image.get_display_url }}" /> </a> <p class="photologue-image-caption">{{ image.caption }}</p> </div>

  • templatetag
  • markdown
  • wiki
  • photologue
Read More

Simple Signal to denormalize vote counts in django-voting

This attaches a signal to the save and delete signals for the Vote object and recalculates the score for the object and stores it in that object's vote_score attribute. This allows you to have a list of those objects and not have to calculate in the database the vote score for each object.

  • voting
  • denormalization
Read More

Admin Hack: Quick lookup of GenericForeignKey id by ContentType

Generic Relations with django.contrib.contenttypes.generic.GenericForeignKey work well for models but the admin interface just shows the object id as an integer with no easy way to lookup the id of a new object. This jquery javascript adds a "Lookup <ContentType Name>" link next to the object id field in the admin interface. This is done by reusing the showRelatedObjectLookupPopup() function provided with django which is used when the field is included in raw_id_fields (a little magnifying glass linked to popup object selector shows up). This essentially works the same way but changes which model's objects are shown and selected in the popup based on the ContentType selected for object_type

  • javascript
  • admin
  • jquery
  • genericforeignkey
  • lookup
  • contenttype
  • object_id
  • raw_id
  • popup
Read More

Decorator to limit request rates to individual views

Example: @limit("global", 3, 10, per_ip=True) def view(request, ...): The example limits the view to one request every 3 seconds per ip address. The limit is shared by every view that uses the string "global" (first parameter), which is an arbitrary string. Request succeed until the accumulated requested time in seconds (second parameter) exceeds the limit (third parameter).

  • request
  • rate
  • limit
Read More

CSRF this!

A form with built-in CSRF protection. Include CsrfCookieMiddleware in your MIDDLEWARE_SETTINGS, subclass SafeForm and off you go. See: [this django-developers post](http://groups.google.com/group/django-developers/browse_thread/thread/2c33621003992d07?hl=en) for more info. [edit] This form is actually WAY overengineered currently. Will update soon.

  • forms
  • csrf
Read More

feedburner middleware

This middleware redirects the request for yoursite.com/feed/whatever/onefeed to your feedburner *onefeed* feed. Having ``FEEDBURNER = ('SomeName', ('blog', 'comments', 'tag1'))`` will use the feedburner feeds at http://feedproxy.google.com/SomeName/blog http://feedproxy.google.com/SomeName/comments http://feedproxy.google.com/SomeName/tag/tag1 you can add more tags, or even intersection and union of them the same way (thanks to piranha for the idea of a middleware) **Update:** now it works for tags as well

  • middleware
  • feedburner
Read More
Author: V
  • 3
  • 10

3110 snippets posted so far.