Login

All snippets written in Python

Snippet List

Template filter to convert timecodes into links

This template filter, "jumptime" will find any timecodes in a chunk of text and convert them to links that can be used to jump a video player to that point. E.g., If there is the string "3:05", it will be converted into a link that can be used to jump to that point. This is similar to what youtube does. For information on how to implement, see Django's [custom template tag information](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags). You'd use this with some javascript like this: `jQuery(document).ready(function(){ jQuery('a.jumpToTime').bind('click',function(){ player.sendEvent('PLAY'); player.sendEvent('SEEK', jQuery(this).attr('value')); }); });`

  • regex
  • time
  • re
  • timecode
Read More

Facebook shell

This adds an 'fbshell' management command which starts up a Python shell with an authenticated [pyfacebook](http://code.google.com/p/pyfacebook/) instance ready to make requests. This is very useful for testing out facebook requests or performing administration tasks without hooking a debugger into your application. This snippet should be saved to /yourproject/management/commands/fbshell.py See [custom management commands](http://docs.djangoproject.com/en/dev/howto/custom-management-commands/) for a description of how this works. If you are already using pyfacebook in your app then you'll already have the right settings, so just run : $ python manage.py fbshell A browser window will pop up, prompting you for authentication (unless you're already logged in to facebook). Press enter in the shell when you're finished this, and you'll be dropped into a shell with the session key, uuid, and name printed. Now you can use the facebook instance: >>> facebook.friends.get() >>> [...] If you haven't used pyfacebook in your app, you'll need at least the following settings in your settings.py FACEBOOK_API_KEY = 'your_api_key' FACEBOOK_SECRET_KEY = 'your_secret_key'

  • management
  • shell
  • facebook
  • command
Read More

truncatechars filter

Truncates a string after a certain number of chars. Question: > *Why don't you use the built-in filter slice?* I need the "three points" (...) only when it really truncates.

  • template
  • filter
  • truncatewords
Read More

ScriptPrefixMiddleware

Adds http://hostname or https://hostname before every URL generated by a Django url function. **Example:** Normally, something like YourModel().get_absolute_url() would return `/2009/09/02/slug`. However, this is not an absolute URL, because it does not include an HTTP schema or host. With this middleware, YourModel().get_absolute_url() will return `http://yourdomain.com/2009/09/02/slug`. This will also work for calls to reverse() or the {% url %} template tag. **Installation:** Drop this code into yourproject/middleware/scriptprefix.py. **Usage:** In your settings.py, add: MIDDLEWARE_CLASSES = ( # ... 'yourproject.middleware.scriptprefix.ScriptPrefixMiddleware', # ... )

  • url
  • domain
  • get_absolute_url
  • host
  • set_script_prefix
Read More

Get object/list or None

1. Function - get_obj_or_none Returns an object or a None Value 2. Function - get_list_or_none Returns a list object or None Value

  • "get_obj_or_none"
  • "get_list_or_none"
Read More

Arbitrary length formset

A formset class where you can add forms as you discover the need within your code. There is also the ability to add ManagmentForm fields. If you ever found yourself in a situation where 1) you have repeated forms that need to be displayed in different locations, or 2) if you find the application logic works better if you add forms as you discover you need them, this code will help you out. Below is pseudo code based on a real implementation I used. Each form had a save button and the SELECTED_PAYMENT field was set through JavaScript. It is very difficult to use JavaScript with repeated forms, without using a formset. from myProject.myApp import myFormsUtils from myProject.myApp.forms import PaymentForm SELECTED_PAYMENT = 'SELECTED_PAYMENT' # extra_fields format: {Field name: (Field type, Initial value)} l_extra_fields = {SELECTED_PAYMENT: (forms.IntegerField, -1)} PaymentFormSetType = myFormsUtils.formset_factory(PaymentForm, extra=0, extra_fields=l_extra_fields) if request.method == 'POST': paymentFormSet = PaymentFormSetType(data=request.POST) if paymentFormSet.is_valid(): li_curFormIdx = pagaFormSet.management_form.cleaned_data[SELECTED_PAYMENT] paymntForm = paymentFormSet.forms[li_curFormIdx] ... do stuff ... # To generate the formset paymentFormSet = PagamentoFormSetType() # You can re-add a form retrieved (as in the one above) l_form = paymentFormSet.add_form(paymntForm) # Or use the add function just like creating a new form l_form = paymentFormSet.add_form(personID=argPersonID, propID=argPropID, year=argYr, amt=lc_Amt) I then stored the `l_form` variables above directly into a unique Context structure and displayed them each individually in my template. Of course this also meant that I also had to output the `paymentFormSet.management_form` explicitly within my template. EDIT 09-11-2009: Modified the initial_form_count() method to properly handle initial form values in conjunction with dynamically added forms.

  • form
  • formset
  • factory
  • arbitrary-length
Read More

A view for downloading attachment

This view snippet is a helper for implementing file download handlers. There is a standard to encode Unicode filenames properly, but many browsers have different protocols. The default encoding is assumed to be UTF-8.

  • view
  • attachment
  • send-file
  • download-file
  • mimetype
Read More

Save a model using an arbitrary db connection

This function lets you save an instance of a model to another database based on a connection argument. Useful when doing data migrations across databases. Connection is anything that would work as a django.db.connection I'm not sure if this handles proxy models or model inheritance properly, though.

  • multi-db
  • connection
Read More

Fix duplicate first page of paginated results

Search engines might conclude there's duplicate content if `/some_view/` and `/some_view/?page=1` returns the same results. This middleware redirects `?page=1` to the URL without the page parameter. You can set the name of the parameter in settings.py as `PAGE_VAR`. See [here](http://www.muhuk.com/2009/08/a-civilized-way-display-lots-of-data/) for more details.

  • middleware
  • pagination
  • seo
  • paginate
Read More

Persistent connection to PostgreSQL database

Hi, I made some small custom psycopg2 backend that implements persistent connection using global variable. With this I was able to improve the amout of requests per second from 350 to 1600 (on very simple page with few selects) Just save it in the file called base.py in any directory (e.g. postgresql_psycopg2_persistent) and set in settings DATABASE_ENGINE to projectname.postgresql_psycopg2_persistent This code is threadsafe, however because python don't use multiple processors with threads you won't get bit performance boost with this one. I really recommend using it in daemon mode. In apache mod_wsgi just set processes=8 threads=1

  • database
  • connection
  • persistent
Read More

WebFaction fixes middleware

On WebFaction, each host has it's own Apache instance, with WebFaction's main Apache instance forwarding requests. This is very useful but means that some of the original information is lost. This middleware should be installed at the top of your list to restore this lost info. It includes the functionality that used to be in SetRemoteAddrFromForwardedFor before it was removed from Django.

  • middleware
  • ssl
  • webfaction
  • https
Read More

TinyMCE Widget

Widget for TinyMCE 3.2.6, a WYSIWYG HTML editor for `textarea`. **Note:** > This snippet uses the TinyMCE package thats contains special jQuery build of TinyMCE and a jQuery integration plugin. Anyway, is easily to adapt to standard package. Usage example: from django.contrib.flatpages.admin import FlatpageForm class MyFlatPageForm(FlatpageForm): content = forms.CharField(widget=TinyMCEEditor()) [TinyMCE download page](http://tinymce.moxiecode.com/download.php)

  • forms
  • wysiwyg
  • form
  • widget
  • modelform
  • tinymce
Read More

2956 snippets posted so far.