Login

All snippets

Snippet List

Improved Button Admin

An improved version of http://djangosnippets.org/snippets/1016/ which lets you add separate buttons for change_list and change_form pages in the admin.

  • admin
  • buttons
Read More

Clean Reversion History: Remove unimportant Changes

If you use this pattern to track changes in the auth user table: from django.contrib.auth.models import User from reversion.helpers import patch_admin patch_admin(User) you can't see important changes, since a version is created for every login if a user. If you want to get rid of changes which only change unimportant stuff you can use this middleware. This middleware can be used for every model. Just use this pattern in your settings: REVERSION_CLEAN={ 'django.contrib.auth': {'User': ['last_login']}, }

  • reversion
Read More

Dump a model instance and related objects as a Python data structure

This utility makes a text dump of a model instance, including objects related by a forward or reverse foreign key. The result is a hierarchical data structure where * each instance is represented as a list of fields, * each field as a (<name>, <value>) tuple, * each <value> as a primitive type, a related object (as a list of fields), or a list of related objects. See the docstring for examples. We used this to make text dumps of parts of the database before and after running a batch job. The format was more useful than stock `dumpdata` output since all related data is included with each object. These dumps lend themselves particularly well for comparison with a visual diff tool like [Meld](http://meldmerge.org/).

  • serialize
  • dump
  • model
  • instance
Read More

django piston use origin django auth

Django-piston have two build-in authentication handlers, the HttpBasicAuthentication and OAuthAuthentication. This snippet give another choice which use the django auth. It can support ajax and normal request.

  • django
  • auth
  • piston
Read More

Decorating class-based views

This is a simplest approach possible. `as_view()` is replaced, so that it applies the given decorator before returning. In this approach, decorators are always put on top - that means it's not possible to have functions called in this order: B.dispatch, login_required, A.dispatch NOTE: By default this modifies the given class, so be careful when doing this: TemplateView = view_decorator(login_required)(TemplateView) Because it will modify the TemplateView class. Instead create a fresh class first and apply the decorator there. A shortcut for this is specifying the ``subclass`` argument. But this is also dangerous. Consider: @view_decorator(login_required, subclass=True) class MyView(View): def get_context_data(self): data = super(MyView, self).get_context_data() data["foo"] = "bar" return data This looks like a normal Python code, but there is a hidden infinite recursion, because of how `super()` works in Python 2.x; By the time `get_context_data()` is invoked, MyView refers to a subclass created in the decorator. super() looks at the next class in the MRO of MyView, which is the original MyView class we created, so it contains the `get_context_data()` method. Which is exactly the method that was just called. BOOM!

  • decorator
  • class-based-views
  • decorating
  • cbv
Read More
Author: lqc
  • 0
  • 2

iCal for Google Calendar

This code publishes an iCal file that can be subscribed to in Google Calendar. They change the way they interpret iCal data occasionally, so this may break, I'll try to keep it up to date. There is some crazy string replace stuff going on there, I haven't yet convinced vObject to format things properly. Feedback welcome. *Note: this works for my existing feeds, but if I add a new feed to GCal, the timezones are incorrect, I'm working on that.

  • calendar
  • timezone
  • google
  • publish
  • ical
  • subscribe
Read More

Validating Model subclass

If you inherit from ValidatedModel instead of from models.Model, then full_clean() will be called before save(). So, add validators to your field definitions, and all your fields will be validated before they go to the database. The same thing can be accomplished with a pre_save signal, but the code is quite a bit messier than the simple inheritance above.

  • model
  • validation
  • subclass
Read More

Take a django.core.mail email message and replace any MEDIA_URL-served images with attached images

The code here will take an EmailMessage from django.core.mail and replace the sourcing of any images served by the application with attached image content. Note: This expects a valid closing tag of **/>** on img elements, it will not properly handle filenames with **'** characters in it, and it does not handle if invalid image sources are listed.

  • email
  • attachment
Read More

Jquery ajax csrf framework for Django

1. Framework to extend the jquery ajax() function to construct post requests that contain a csrf token. 2. The example view used with the framework takes JSON data and returns JSON data containing either: 3. "success" with a message and additional dictionary of JSON data to use in the page 4. "error" with an error message. 5. The ajax function framework satisfies Django's csrf requirements by injecting a csrf token into the post requests created using the function. This example is a form with ~160 fields that we wanted to help fill in customer information to automatically. 1. User calls the lookup() script from the onblur attribute of the customer_id form field by leaving the field. 2. The lookup script takes the contents of the customer_id formfield and uses the jquery ajax() function to construct a JSON post request to the "/json /?act=" url. 3. The json view takes actions as get requests. We pass the post request to the JSON url already including the get request. "/json/?act=lookup" 4. The jquery framework in the snippet includes a csrf token in the ajax request automatically. 5. The customer_id is passed as JSON to the json view lookup action and customer details are attempted to be looked up in the database. 6. If successful the request returns a JSON dictionary of customer details which are pushed into the formfields using javascript in the lookup() function. The end result is if the user fills out the customer_id field of the form first (which we suggest with tooltip overlay) the customer name and address information will populate automatically. *Credit to Guangcong Luo https://github.com/Zarel

  • json
  • jquery
  • csrf
Read More

Redirect to no slash

The canonical notion of urls ending in slashes dates from a web where urls were used to access documents and files this is no longer the case so keeping your urls witouth trailing slashes makes them prettier. The problem is that many people/blogs/spiders/browsers could end up with a url with slashes which can be problematic for you SEO, or confuse users. This script is for sites with no trailing slash dicipline in their urls, and to prevent everybody getting a horrible 404 for a simple slash you just got to remove it and issue a permanent redirect (301) and you'll get your pretty urls your cake and eat it too. I must stress, you will have to edit all your public urls removing the slashes like so: url(r'^login$', login,} If you forget, to edit them and visit the url, your browser will remember the redirect and you'll have to clean the browsing history to fix it.

  • permanent redirect
  • no slashes
  • no slash
Read More

3110 snippets posted so far.