Login

Most bookmarked snippets

Snippet List

Date Picker Template Include

All you need to do is include the file you save this as in your other templates. The css and javascript is right in the file. Fully customizable. Very easy. Click a date to choose a single date. Click a second date to choose a range. A third click will act as a first click. note: you also will want to customize the django template specific variables in elements with ids: s_date e_date cal_month if you change those, it's not even really django specific, but i use this in my form for time off requests at work.

  • template
  • date
  • picker
  • include
Read More

Child aware model inheritance

Base models aren't aware of its inherited models, here is a quick solution to access child models from the base model.

  • model
  • inheritance
  • child
  • content-type
Read More
Author: rix
  • 2
  • 4

Securely Signed S3 Links With Expiration

I couldn't find a Python implementation of this, so I threw this class together real quick. This will let you share "private" files on S3 via a signed request. It will also have an expiration on the link, so it is only valid until a certain time period. Example Usage: s3 = SecureS3('AWS_ACCESS_KEY', 'AWS_SECRET_ACCESS_KEY') s3.get_auth_link('your_bucket', 'your_file') That would return your secure link. eg, http://your_bucket.s3.amazonaws.com/your_file?AWSAccessKeyId=AWS_ACCESS_KEY&Expires=1226198694&Signature=IC5ifWgiuOZ1IcWXRltHoETYP1A%3D

  • s3
  • secure
Read More
Author: pjs
  • 1
  • 4

ajax error sink

Often its useful to get error information for ajax/javascript errors happening on various clients. This can go to something like this: # error_sink def error_sink(request): # post request, with event name in "event", and event data in "data" context = request.REQUEST.get("context", "") context = cgi.parse_qs(context) context["data"] = cgi.parse_qs(context.get("data", [""])[0]) context["user"] = request.vuser context["referrer"] = request.META.get('HTTP_REFERER', "referrer not set") context = pformat(context) send_mail( "ajax error", context, "[email protected]", ["[email protected]",], fail_silently=True ) return JSONResponse({"status": "ok" }) # }}}

  • ajax
  • jquery
  • error
  • reporting
Read More

Twisted protocol for receiving logging module messages over a socket

When using Python's logging module in a concurrent environment (e.g. mod_python), messages get dropped by the standard file-based handlers. The [SocketHandler](http://www.python.org/doc/2.5.2/lib/node414.html) allows you to send logging messages to a remote socket. This snippet provides code for listening for such messages and writing them out to a log file. The final log file is configured as a standard logging file-based handler.

  • logging
  • twisted
Read More

Jinja2 integration + application specific functions/filters/tests

Jinja2 is an alternative template system that can be plugged into django. It offers greator flexibility in presentation logic; if you find the django template system too restrictive, you should have a look at Jinja2 (The syntax is very similar). In Jinja, you don't need costum tags (most of the time), because you can call functions and pass them parameters too! The only problem is that you cannot "load" functions from the template, this "loading" must be done by the code that renders the template. Same goes for filters and tests. If you need only two or three functions/filters, no problem, you can manually add them to the Environment object; but this method doesn't really scale with real-life webapps. This module/snippet offers a solution by allowing the user to define application-specific functions and filters and load them into the jinja2 environment automatically. Here's how to use this: 1. Install Jinja2 (for a quick & dirty installation, you can just put the jinja2 folder in a folder that's in PYTHONPATH) 2. Save this python module somewhere and call it something meaningful (I have it as jinja.py in my project directory) 3. Whenever you need to respond (an HttpResponse) with a template that's rendered by jinja, import this module and call `return jrespond( template_name, context )` 4. Any filters or functions you define in any of your applications will be readily available inside the template (see the documentation in code)

  • template
  • templates
  • jinja
  • template-tags
  • jinja2
Read More

SignedForm: CSRF-protect forms with a hidden token field

This form subclass helps protect against cross-site request forgery by adding a hidden field named `csrf_token` to forms. The form must be initialized with the request as a keyword argument, both with and without POST data: my_form = MySignedForm(request=request) ... my_form = MySignedForm(request.POST, request=request) Upon validation, a `PermissionDenied` exception will be raised if forgery is detected. If any security details have been overlooked in this recipe, please leave a comment.

  • forms
  • csrf
Read More

Making prepopulate_from work with ForeignKeys and other sorts of choice fields

This is a fairly small bit template that, if placed in your_project_dir/templates/admin/prepopulated_fields_js.html will override the template that is normally pulled by the preopulated fields templatetag in the admin. The result is that you can successfully specify a ForeignKey or other field involving choices as a source for prepopulate_from in your admin.py. It works just as well when there are multiple fields of both the text and choice variety.

  • javascript
  • admin
  • prepopulate
Read More

autotranslate po files using google translate

Save to autotranslate.py, run using python autotranslate.py pofile inputlang outputlang, eg. python autotranslate.py path_to_blank_fr_lang.po en fr, to translate to french. Some known bugs: * Doesn't handle some line returns properly * Block translations aren't formated correctly in the translation. If anyone has any issues or fixes please post to the comments. Of course the output shouldn't be used as substitute to a proper translation.

  • translation
Read More

Something like list_detail generic view but returns PDF document instead

This should work as a `django.views.generic.list_detail` generic view but will produce PDF version of given template. This code is merged code from perenzo's [example](http://www.djangosnippets.org/snippets/659/) and code from `django.views.generic.list_detail` module. `pisa` package is required from (http://www.htmltopdf.org/download.html) with `html5lib` package and Reportlab Toolkit 2.1+ NOTE: this is code for Django 0.96. In Django 1.0 change in line 3: ObjectPaginator to Paginator

  • generic-views
  • pdf
  • html
  • css
Read More

render_partial

Works much like an inclusion_tag but allows the template_name to be given as an argument or defaults to partials/MODELNAME.html where MODELNAME is 'got' from the context object you want to render. Its very rough so improvements very welcome! It would be nice to be able to pass new context variables as template tag [keyword] arguments for use in the template to be rendered so you basically have a template tag equivalent for render_to_string... Example usage in a template: {% render_partial post %} or {% render_partial post partials/super_post.html %}

  • template
  • tag
Read More

djangopath: conveniently set sys.path and DJANGO_SETTINGS_MODULE

In the past, whenever I had a script that I wanted to properly configure the settings for, I would use something like the following idiom at the top of the script: import sys, os; dirname = os.path.dirname # sys.path.insert(0, dirname(dirname(__file__))) sys.path.insert(0, dirname(__file__)) os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings' Notice that this is a relative setting to `__file__` variable in the script. The djangopath function is an attempt to do away with the above such that I can now write the following: from lib import djangopath; djangopath(up=2, settings='myapp.settings') This seems to work for me, but it assumes that you are packaging your script inside your projects/apps. If they are elsewhere then you may need to resort to another method (e.g. absolute paths, etc.) AK

  • settings
  • path
Read More

Serve static media files from app/media subdirectory

This view will serve media files from all media subdirectories of apps in your INSTALLED_APPS setting. Save the view as media.py in your django site folder and add to urls.py: if settings.DEBUG: urlpatterns += patterns('', (r'^media/(?P<appname>\w+)/(?P<path>.+)$', 'devel_site.media.serve_apps') )` Now suppose your installed apps setting looks like: INSTALLED_APPS = ('org.myself.myapp', ...) Then a request to http://localhost/media/myapp/directory/file.css will serve the file org/myself/myapp/media/directory/file.css.

  • media
  • static-media
Read More

3110 snippets posted so far.