Login

All snippets

Snippet List

RFC: Shim to allow view classes rather than functions

This snippet is working code, however it is not intended for proper use, rather to garner comment on an alternative style of view - using a class for views, rather than a function. While working with views, I've often felt that the traditional django code layout splits concerns in an unnatural fashion. The parameters for a view must be maintained in both the urls file as well as the view for example, and there is no neat way of grouping multiple accessor for a REST resource. This 'shim' code aims to propose an alternative architecture, that is interchangeable with the existing system. Rather than include a tuple of urls, instead a list of classes is provided. Each class models a resource, or page. Page objects have a url property and name property, so it is therefor trivial to reconstruct the url tuple from the class, but allow more simplicity and structure in relating the methods of the resource. You may notice that this structure closely follows the architecture of the web.py framework - this syntax did indeed play a part in the concept for such a structure. While this paradigm may not be suitable in all situations, I believe it promotes a simpler, more encapsulated views architecture. Any comments and feedback are welcomed. Example usage (untested, sorry): class Homepage(Page): def get(request): return HttpResponse("Hello World") urlpatterns = patterns('', Homepage, url('^existing$', existing.view.function, name = "foo"), )

  • views
  • rfc
Read More

truncatestring filter

Simple filter that truncates string to specific number of letters. Example usage in template: `{{ myvariable|truncatestring:20 }}` if myvariable is "That is my long string", the result will be: "That is my long s...". Put the code into templatetags/.

  • filter
  • string
Read More

Twitter oAuth example

**UPDATE**: A more complete example is up on [GitHub](http://github.com/henriklied/django-twitter-oauth/tree/master) Based around Simon Willison's [Fire Eagle oAuth](http://www.djangosnippets.org/snippets/655/), this will allow you to develop Twitter oAuth applications (…that is – if you're in the closed beta)

  • twitter
  • oauth
Read More

themed_template_loader

I developed this template loader for adding themes support in [gitology](http://www.amitu.com/gitology/). In order to support theming django applications, add this template loader at as the first TEMPLATE_LOADERS settings.py setting. Anywhere you request base.html, blog/index.html, when the theme is set to "bw", it will look for bw/base.html or bw/blog/index.html files first. Takes care of both render_to_response() in view or {% load template %} in templates.

  • templateloader
  • theming
Read More

SSL Decorator

Wrote this some time ago when I couldn't find one already completed. Came up in the IRC channel so I decided to post it. Easy enough to use. `from ssldecorator import ssl_required` `@ssl_required` `def your_view(request):` ` ''' your code here '''` You can place a variable in your settings.py to change the SSL domain (ie, if you have SSL running on secure.yourdomain.com instead of www.yourdomain.com).. `SSL_DOMAIN = 'https://secure.yourdomain.com'` Note: please include a proper URL. If https isn't used, the decorator will add it.

  • ssl
  • decorator
Read More
Author: pjs
  • 2
  • 7

Smart {% if %} template tag

Save this as `smart_if.py` in the `templatetags` folder of one of your apps. Then a simple `{% load smart_if %}` replaces the boring built-in Django `{% if %}` template with the new smart one. *7 May 2009*: Was asked about whether it handles combination of and/or. It does, added a test to show it. I actually like how Django doesn't let you do this, but I'm not going to confuscate my code for a restriction like this. *15 June 2009*: Fixed up a bug with boolean precedence (`x or x == 0` was being parsed as `(x or x) == 0` instead of `x or (x == 0)`). Add some extra test cases, including some for invalid cases.

  • if
  • smart-if
  • if-in
  • greater-than
  • less-than
Read More

Hide Emails

Example Usage in the template: <p>{{ email|hide_email }}<br /> {{ email|hide_email:"Contact Me" }}<br /> {% hide_email "[email protected]" %}<br /> {% hide_email "[email protected]" "John Smith" %}</p> {{ text_block|hide_all_emails|safe }} All hidden emails are rendered as a hyperlink that is protected by javascript and an email and name that are encoded randomly using a hex digit or a decimal digit for each character. Example of how a protected email is rendered: <noscript>(Javascript must be enabled to see this e-mail address)</noscript> <script type="text/javascript">// <![CDATA[ document.write('<a href="mai'+'lto:&#106;&#x6f;&#x68;&#x6e;&#x40;&#101;&#120;&#97;&#109;&#x70;&#108;&#x65;&#46;&#x63;&#111;&#109;">&#74;&#111;&#104;&#110;&#x20;&#83;&#x6d;&#x69;&#x74;&#104;</a>') // ]]></script>

  • email
  • hide
  • protect
Read More

Fuzzy Date Diff Template Filter

Pass in a date and you get a humanized fuzzy date diff; e.g. "2 weeks ago" or "in 5 months". The date you pass in can be in the past or future (or even the present, for that matter). The result is rounded, so a date 45 days ago will be "2 months ago", and a date 400 days from now will be "in 1 year". Usage: * `{{ my_date|date_diff }}` will give you a date_diff between `my_date` and `datetime.date.today()` * `{{ my_date|date_diff:another_date }}` will give you a date_diff between `my_date` and `another_date` Make sure to install this as a template tag and call `{% load date_diff %}` in your template; see the [custom template tag docs](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/) if you don't know how to do that.

  • template
  • filter
  • date
  • humanize
Read More

Reusable Logging

"Thus, if a LOGGER is configured inside settings.py, we use that. Otherwise, we just use vanilla logging functions with the global logging configuration. Nice and sweet." Naturally, the logger can be anything described [here](http://docs.python.org/library/logging.html), I'm just using the RotatingFileHandler as an example because that's what I was using in my project. Full write up+shamless plug [here](http://mihasya.com/blog/?p=237)

  • logging
Read More

Pagination shortcut

This is a function wrapping the code from [example](http://docs.djangoproject.com/en/dev/topics/pagination/#using-paginator-in-a-view) from django docs. The required parameters are: `request` which is a `Request` object from a view, and `objects` - a list of objects to paginate. You may want to tune number of items per page by specifying `count` and the name of a GET parameter through `param_name` To use it in your view just wrap the paginated object into a function for example: def someview(request): articles = Article.objects.all() ... some other logics ... return render_to_response(template, {'articles': paginate(request, articles)}

  • pagination
Read More

Nested commit_on_success

This is a simple modification to the standard transaction.commit_on_success decorator that is aware of existing transactions. If a managed transaction is already active then the wrapped function is called directly, assuming the active transaction will clean up as appropriate. Otherwise, a standard commit_on_success is performed. I'm using this to wrap the save() method of models that manipulate other related models on save, e.g: @nested_commit_on_success def save(self): super(MyClass,self).save() for m in other_models: self.fix_up_other_model(m) m.save()

  • transaction
Read More
Author: rfk
  • 2
  • 1

DateTimeField with microseconds

Use this in your form if you want to accept input in microseconds. In a ModelForm you can override the field like this: def __init__(self, *arg, **kwargs): super(MyForm, self).__init__(*arg, **kwargs) self.fields['date'] = DateTimeWithUsecsField() *Update* May 26 2009 - Updated to address a couple issues with this approach. See http://code.djangoproject.com/ticket/9459

  • forms
  • datetimefield
  • microseconds
Read More

Language-aware template inclusion

Looks up for a template based on the template-name plus the current users language code. Loads the template and renders it with the current context. Example:: {% langinclude "foo/some_include.html" %} Based on the users LANGUAGE_CODE, assumed we have 'de', it tries to render the template 'foo/some_include.html.de'. If that doesn't exists, it renders the template 'foo/some_include.html'. This is the default behavior of the include-Tag. Basically this is a shortcut for the following code, just with a fallback for the default template:: {% ifequal LANGUAGE_CODE "de" %} {% include "foo/some_include.html.de" %} {% else %} {% include "foo/some_include.html" %} {% endifequal %} --- Ein deutscher [Weblogeintrag mit Beschreibung](http://www.mahner.org/weblog/sprachabhangige-template-imports/)

  • templatetag
  • i18n
  • language
  • include
Read More

Readonly fields on Form/Modelform

A Form and ModelForm which provides the ability to specify certain fields as readonly, meaning that they will display their value as text wrapped with a <span> tag. The user is unable to edit them, and they are protected from POST data insertion attacks. The recommended usage is to place a NewMeta inner class on the form, with a readonly attribute which is a list or tuple of fields, similar to the fields and exclude attributes on the Meta inner class. class MyForm(ReadonlyForm): foo = forms.TextField() bar = forms.TextField() class NewMeta: readonly = ('foo',) Use these forms as you would a standard form in your templates.

  • forms
  • field
  • readonly
  • modelforms
  • span
Read More

3110 snippets posted so far.