Login

All snippets written in Python

Snippet List

Calendar template-tag

Simple template tag to show a calendar. I use it to display events (which is a model with a start_date and end_date attribute. You probably should change this according to your needs.

  • template
  • tag
  • calendar
Read More

Captcha Middleware

A middleware we are using to stop "spam" on Curse. It makes the user fill in a captcha box whenever they submit a form unless a cookie is set (which expires by default after 6 hours) See also [the template](http://www.djangosnippets.org/snippets/128/) Note: render_template is simply a shortcut function we have for doing render_to_response with a request context

  • captcha
  • anti-spams
Read More

truncate letters

filter for truncating strings similar to truncatewords only with letters.

  • filter
  • truncate
  • letters
Read More

Export models as json

I use this script to export a group of models that I want to import later as initial data. It exports them as serialized json, which is perfect for importing later with the loaddata function in manage.py.

  • json
  • loaddata
  • export
  • fixtures
Read More

IfValueTag

Don't repeat yourself: when you wish to have a block of html with a variable value, but only if the variable is set, you can do this: {% ifvalue company.contact.email as email %} <h3>Email address</h3> <a href='mailto:{{ email }}'>{{ email }}</a> {% endifvalue %} Instead of this: {% if company.contact.email %} <h3>Email address</h3> <a href='mailto:{{ company.contact.email }}'>{{ company.contact.email }}</a> {% endifvalue %} The tags ifvalue and ifnotvalue are provided by this snippet. If you don't specify `as somename`, then the variable's value will be assigned to the name "value".

  • tag
Read More

Strip html comments middleware

Middleware for stripping all html comments from the response content before returning it to the client. This will also strip inline javascript with htmlcomments put around it!

  • middleware
  • comments
Read More

BritishDateField

The date field in the newforms module includes American style mm/dd/yyyy , which anyone outside the US will recognise as being complete madness. This date field behaves sensibly.

  • newforms
Read More

TemplatedForm

Newforms are made to make any kind of customizations easy. Sometimes standard methods of rendering HTML/XML/other content of the django.newforms is not enough to completely satisfy all web design needs so you may want to present forms in own templates. Using templates to render output as HTML or XML is straighforward, and in many cases easier then using standard approach. Step by step usage guide: 1. Create file in your project yourproject/utils/newforms.py and place Class TemplatedForm there 2. Create newforms subdirectory in templates dir, and post 2 templates there (form.html, field.html) from the documentation code for TemplatedForm class 3. Inherit from TemplatedForm in your form class to use this form.

  • template
  • newforms
Read More

An XML-RPC Decorator

Drop this package wherever you want, import the decorator, and use it with one argument to decorate any function you want (`@xmlrpc('pingback.ping')`). That function is now available on your XML-RPC interface, available through this view. Make sure to provide the view (`call_xmlrpc`) with a URL so that it's accessible.

  • xml-rpc
Read More

Markdown and Syntax Highlighting in Django

This is a [Django template tag](http://www.djangoproject.com/documentation/templates_python/#extending-the-template-system "Extending the template system") that renders an arbitrary block of text with Markdown and [Pygments](http://pygments.org "Syntax highlighter"). Use Markdown as usual, and when you have a code block to insert, put it inside `code` tags, with the language as the class: `<code class='python'>print "Hello, World"</code>` To use it in a template, first `{% load ... %}` the tag library, then `{{ content|render }}` your content. The tag takes one optional argument, to enable safe rendering in markdown. To use it, call `{{ content|render:"safe" }}`.

  • pygments
  • markdown
  • syntax-highlighting
  • template-tag
Read More

Django Using Stored Procedure

Here is an clean example of using stored procedure using django. It sounds pretty weird "stored procedures in django" but for legacy database system we still need a clean approach to implement stored procedures using django. In this example, I've implemented logic inside models.py by creating a dummy class, i.e a django table (which is comparable to package in your database) and inside this package/class i added stored procedure wrappers. I tested it with boulder-oracle-sprint branch, there is minor issues with LazyDate in db/backend/oracle/base.py but it still working after minor edits in base.py. It worked absolutely fine with MySQL and MSSQL. View is pretty straight forward. Dont forget to create form.html as template and in body just put {{ form }}

  • django
  • stored
  • procedures
  • oracle
  • mysql
Read More

simple text image view

**Credit goes to** [Andrew Gwozdziewycz](http://www.23excuses.com/2006/Jun/30/simple-django-view-for-dynamic-text-replacement/) and [Jacob Kaplan-Moss](http://www.jacobian.org/writing/2006/jun/30/improved-text-image-view/) This is basically their code. Only differences: * orientation can be customized * size can be customized * GIF-Image with transparency is created Note: Because of the minimum palette that's used, the font isn't antialiased/smoothened. My url for this view looks like so: (r'^img/(?P<fontalias>\w+)/(?P<orientation>(normal|left|right))/$', 'view.text_to_image')

  • text
  • image
  • text-image-view
Read More

Days Since Filter

Very simple filter that returns one of the following by default: 1. \# days ago 2. yesterday 3. today 4. January 01, 2007 Example template code: This thread was started {{ post.date_created|dayssince }}. This thread was started today. E-mail sent: {{ email.date_sent|dayssince|capfirst }} E-mail sent: Yesterday Object created: {{ obj.date_created|dayssince|upper }} Object created: 12 DAYS AGO User's bogus birthday: {{ user.get_profile.bday|dayssince }} User's bogus birthday: April 20, 3030

  • filter
Read More

Newforms customs validators

How to proceed to add a custom validator to a newforms field : you just need to create a new class derivated from forms.YourField with a custom clean method. Do not forget the line super(UserField, self).clean(value) ; in our case, it verifies the field attributes : min_length, max_length or required. More explications (in French) : [des validateurs personnalisés pour Django](http://www.aozeo.com/blog/67-django-newforms-validateurs-personnalises)

  • newforms
  • validators
Read More

Modelaware json serializer

A serializer that handles dicts with querysets and model instances, nice to use if you have a paginator context. paginate_by = 8 paginator = ObjectPaginator(queryset, paginate_by) page = request.GET.get('page', 1) try: page = int(page) object_list = paginator.get_page(page - 1) except (InvalidPage, ValueError): if page == 1 and allow_empty: object_list = [] else: raise Http404 result = { 'object_list' : object_list, 'is_paginated': paginator.pages > 1, 'results_per_page': paginate_by, 'has_next': paginator.has_next_page(page - 1), 'has_previous': paginator.has_previous_page(page - 1), 'page': page, 'next': page + 1, 'previous': page - 1, 'pages': paginator.pages, 'hits' : paginator.hits, } serialize(result, ensure_ascii=False)

  • json
  • serialization
Read More

2955 snippets posted so far.