Login

All snippets written in Python

Snippet List

Manual CSRF check for Django Facebook canvas applications

The way to manually control CSRF correctness for FB applications. Automatic check cannot be used because FB does POST on your canvas URL when initializing your application without CSRF token. If you still want to use Django CSRF stuff do manual checks. You only need to perform manual check when there is no correct signed_request present in your request - correct request means you really deal with FB. Use facebook_csrf_check to verify POST requests when signed_request is absent.

  • django
  • python
  • post
  • facebook
  • csrf
  • fb
Read More

App Display Label Template Filter Workaround

I have been wrestling with custom app labels and have come to the conclusion that this is the easiest workaround for the problem. Since I name most of my apps as Foo_Bar this makes them look a lot nicer. I just apply the filter to whatever app label and it fixes it. If you need a more complex replacement, you could just have an if statement that looks for the full app label and replaces it with whatever you want.

  • template
  • filter
  • app-label
  • app-display
Read More

Configurable defaults for contrib.sites default Site during syncdb

This simple snippet provides a more sensible default for the Site object created during the first pass of syncdb (that is, with a default domain of `localhost:8000`). I made this so that the admin's "view on site" button will work automagically during my development cycle (which often involves dropping and recreating a sqlite database). In addition, it provides 2 options for configuring the default Site as you'd like: settings parameters (`DEFAULT_SITE_DOMAIN` and `DEFAULT_SITE_NAME`) or `kwargs` (the latter takes precedence).

  • django
  • admin
  • sites
  • syncdb
  • contrib
  • manage
  • Site
  • defaults
Read More

BRPhoneNumberWidget

A widget created for BRPhoneNumberField that splits the input into a <input> for the area code and another for the phone number. Usage example: class MyForm(forms.Form): mobile_phone = BRPhoneNumberField( label='Telefone Celular', widget=BRPhoneNumberWidget() ) ...

  • phone
  • br
  • localflavor
  • BRPhoneNumberField
Read More

Auto-documenting Django Models with Sphinx

In my sphinx documentation I really wanted a nice clean list of the fields on my Django models. The most obvious way of doing this is to add ":param blah:" tags to the docstring, but this takes a long time to implement and violates DRY principles when you already have lots of nice help text in the model definition. Another way is to use "#:" comments on attributes, but this approach suffers from the same issues as the previous method with the additional problem of Sphinx crapping out on file and custom fields. So anyway, this is my solution. It uses the Sphinx docstring processing callback to intercept any objects that inherit from django.models.Model and creates a nice param list of all the fields on that model. Param descriptions come from the field's help text or verbose name if no help text is defined. To use this, just add it to the end of your source/conf.py, filling out the project path as appropriate. You may be able to skip the Django environment setup lines if you're adding this to a Sphinx doc that already has Django models set up.

  • sphinx
  • introspection
  • documentation
  • docs
  • autodoc
Read More

Decorating URL includes

Apply a decorator to every urlpattern and URLconf module returned by Django's include() method . This allows you use a decorator on any number of views without having to decorate each one individually. The use case here is wrapping all of the Django Admin with a superuser decorator. This is code that's better left alone where we can't actually go in and decorate the Admin views and urlpatterns manually. It's also almost guaranteed the Admin will include() other URL files. So the added bonus is all the INSTALLED_APPS that have their admin.py files registered by admin.autodiscover() will be decorated automatically as well. This snippet is greatly inspired by [@miracle2k](http://djangosnippets.org/users/miracle2k/)'s excellent [#532](http://djangosnippets.org/snippets/532/). In the comments there @timbroder offers a modification to decorate includes but I think this is cleaner, simpler code and not subject to changes in the Django base code driving _get_url_patterns().

  • urls
  • urlconf
  • decorator
  • urlpatterns
  • resolve
Read More

keeping filter states after edits

When saving an edit to an object from a filtered list view you are, by default, returned to list view without any of your filters applied. This solves that problem, keeping the filtered view in a session variable until you reach a point where the session key is deleted. The solution presented here is hugely based off of other's work with most of the solution gained from: [Admin: return to change_list with filter and pagination applied](http://djangosnippets.org/snippets/2415/ "Admin: return to change_list with filter and pagination applied") This solution offered the best approach in our mind over the others listed here on snippets since the solution didn't require changes to template code...this is completely self contained within your own admin.py files. The advantage to our solution over the above linked solution is that under different use cases the user may or may not be redirected to the filtered list_view. For example, if you edit an object and click the save and continue button, then you would lose the filter when you finally finished editing the object and clicked save. Added on here is a delete of the session key when users add objects, the reasoning we're going this route is we don't want to return users to filtered views when they just added a new object. Your mileage may vary and if so, it's easy enough to fit your own needs. HTHs

  • filter
  • admin
  • change_list
Read More

datemate

This wil format the date to today at 1:03 pm , yesterday at 9:13 pm, 22 August at 10:08 pm

  • datetime
  • date
  • date-format
Read More

madslug

this will turn ikfjji34 iojwe# eijdf#@$iojdfg 234oijdfg into ikfjji_iojwe_eijdfiojdfg_oijdfg

  • text
  • slug
Read More

ByteSplitterField

When you want to save integers to the db, you usually have the choice between 16-, 32- and 64-bit Integers (also 8- and 24-bit for MySQL). If that doesn't fit your needs and you want to use your db-memory more efficient, this field might be handy to you. Imagine you have 3 numbers, but need only 10 bit to encode each (i.e. from 0 to 1000). Instead of creating 3 smallint-fields (48 bit), you can create one 'ByteSplitterField' which implements 3 'subfields' and automatically encodes them inside a 32 bit integer. You don't have to take care how each 10-bit chunk is encoded into the 32-bit integer, it's all handled by the field (see also field's description). Additionally, the Field offers opportunity to use decimal_places for each of your subfields. These are 'binary decimal places', meaning the integer-content is automatically divided by 2, 4, 8, etc. when you fetch the value from the field. You can also specify how values are rounded ('round' parameter) and what happens when you try to save a value out of range ('overflow' parameter) Not implemented (maybe in the future if I should need it sometime): * signed values. All values are positive right now! * real (10-based) decimal places (actually you could probably directly use DecimalFields here) * further space optimization, i.e. saving into CharField that's length can be chosen byte-wise

  • model
  • db
  • database
  • field
  • custom
  • custom-model-field
  • IntegerField
  • multibit-field
  • model-field
Read More

create_c

Instead of creating a dictionary on every view everytime you could do this and just call it like c = create_c(request)

  • templates
  • request
  • data
  • csrf
Read More

Registration with confirmation email

This registers a users taking data from a submitted form, sends a confirmation email, activates the account when the confirmation link is clicked and logs the user in

  • registration
  • email
  • register
  • confirmation
Read More

ultralize

This is a function based on django's urlize modified to show different media based on their url. It supports images, links, mp3/ogg links, youtube videos, vimeo videos and dailymotion videos. I added a switch called mini to have two modes to show things in different places. When mini is activated it will only parse the first url provided and discard the rest as well as limiting the height.

  • html
  • youtube
  • urlize
  • parser
  • vimeo
  • dailymotion
  • url-to-image
  • url-to-video
  • urlze
Read More

Cache view by user (and anonymous)

Use this decorator in your views to cache HttpResponse per user, so each user has his own cache, instead of a shared one as `from django.views.decorators.cache.cache_page` does. Add this to use: from somewhere import cache_per_user @cache_per_user(ttl=3600, cache_post=False) def my_view(request): return HttpResponse("LOL %s"%(request.user)) All documentation inside the decorator are in brazilian portuguese, feel free to translate to english

  • views
  • cache
  • decorator
Read More

2955 snippets posted so far.