Login

All snippets written in Python

Snippet List

JSON instead of pickle for memcached

Standard memcache client uses pickle as a serialization format. It can be handy to use json, especially when another component (e.g. backend) doesn't know pickle, but json yes.

  • memcache
  • cache
  • json
  • memcached
  • pickle
Read More

Save image in field

Small function that i use to save files to an imagefield, the file can be either an url or a file. This function has the following requirements. import requests from django.core.files import File from django.core.files.temp import NamedTemporaryFile from django.conf import settings Get the awesome requests library: pip install requests This function uses MEDIA_ROOT to know the location of the static dir, you can change that chaging the static_dir variable.

  • image field
  • save file
Read More

Multilingual site based on domain - not accept header and django_session

On our site [Fornebuklinikken - A cosmetic surgeon in Norway](http://www.fornebuklinikken.no) we also have a domain [http://fornebuklinikken.com](http://www.fornebuklinikken.no) which should be using the 'en' language. We didn't wan't to use the standard locale lib, and wrote our own middleware which lookups the correct language corresponding to the domain (.no or .com) Any questions? Contact me on herman.schistad (at) gmail.com

  • internationalization
  • middleware
  • multilingual
  • locale
  • domain
  • localeurl
Read More

SOAP web service with soaplib 2.0

I've updated the `DjangoSoapApp` class from [this popular soaplib snippet](http://djangosnippets.org/snippets/2210/) so the snippet will work properly with soaplib 2.0. Usage is the same as before: my_soap_service = DjangoSoapApp([MySOAPService], __name__)

  • soap
  • soaplib
  • wsdl
Read More

manage.py reboot

1) Simply create a "management/commands" folder in one of your INSTALLED_APPS folders. Then add a "reboot.py" file in your "management/commands" 2) In settings.py, you can OPTIONALLY add: PROJECT_NAME = 'Blah' PROJECT_DOMAIN = 'blah.com' These two settings will be used to create a "Site" object as well as a superuser. If you choose not to use these settings, the reboot command simply reverts to using your DATABASES[default] username as superuser. 3) Execute the command via "python manage.py reboot" Enjoy.

  • runserver
  • setup superuser
  • recreate database
  • install fixtures
Read More

Validation for full e-mails (e.g. "Joe Hacker <[email protected]>")

Out of the box, Django e-mail fields for both database models and forms only accept plain e-mail addresses. For example, `[email protected]` is accepted. On the other hand, full e-mail addresses which include a human-readable name, for example the following address fails validation in Django: Joe Hacker <[email protected]> This package adds support for validating full e-mail addresses. **Database model example** from django import models from full_email.models import FullEmailField class MyModel(models.Model): email = FullEmailField() **Forms example** from django import forms from full_email.formfields import FullEmailField class MyForm(forms.Form): email = FullEmailField(label='E-mail address') I maintain this code in a [GitHub gist](https://gist.github.com/1505228). It includes some unit tests as well.

  • forms
  • model
  • email
  • validation
  • orm
  • database
Read More

Template filter to markup form fields with optional args

Template filter to mark-up individual form fields. Usage : In template - {% load form_custom %} then for a form field - {{ form.field|form_row:"default" }} for default wrapper or - {{ form.field|form_row:"lbl_cls=some_class_name&reqd=no" }} to pass option args seperated by & Optional args are :- wrapper_cls - override default field wrapper div class name error_cls - override default field error div class name lbl_cls - override default label_tag div class name label - yes/no default is yes - output label_tag reqd - yes/no default is yes - marks up required fields as bold with label ending with * See code for all default args.

  • filter
  • forms
Read More

Fetching list of SQL queries executed so far for all requests

These snippets together give you the ability to view all Django SQL queries executed across all incoming requests by visiting a particular URL (`/profiling` in the example). This is useful when developing with the Django test server. This is useful if most of the incoming requests are AJAX requests, because in such cases the debug toolbar will not be able to show which queries got executed. The `SqlProfilingMiddleware` class is the key one. At the end of every incoming request it appends the executed SQL queries to a static class member list. Any information request profiling information can be added in this way. The snippet does not add any security around viewing such information. This was done just to keep the code simple. But when implementing this you will definitely want to restrict access to this URL to only people allowed to view such information.

  • sql
  • debugging
  • profiling
Read More

Readonly Tabluar Inline

An Image says more than 100 words: [readonlytabularinline.png](http://img39.imageshack.us/img39/6555/readonlytabularinline.png) Use `editable_fields` to exclude some fields from being readonly.

  • admin
  • tabular-inlines
Read More

Django Sudo

Staff can log in as a user, from a url to help with customer support or debugging.

  • admin
  • user
  • login
  • staff
  • sudo
Read More

Generic object_detail view with multiple named URL filters

This snippet is greatly inspired by [@jlorich](http://djangosnippets.org/users/jlorich/)'s useful [#2436](http://djangosnippets.org/snippets/2436/). The main difference is that I wanted to choose the names of my URL params instead of being forced into naming them "value1", "value2", etc. When reversing the URL you have to remember that the kwargs aren't friendly. By using the same names in the `filters` list, you don't have to change the way your otherwise write the URL pattern. Also it's clear throughout how you'll be filtering the QuerySet. The other change I made was "erroring early". This avoids running the QuerySet all over again inside `object_detail()` just to have it raise an exception we could have caught the first time.

  • filter
  • urlconf
  • generic-views
  • queryset
  • urlpatterns
Read More

2955 snippets posted so far.