Login

Most bookmarked snippets

Snippet List

Django with AngularJS

This is a simpel snippet to prevent conflict between Django and AngularJS template syntax. It is possible to change the AngularJS syntax, but this can cause compatibility problems, so I figured that this was a better solution.

  • AngularJS
Read More

Closure for FieldListFilter classes with custom sets of ranges

This closure lets you quickly produce date-style range filters in the Django Admin interface without having to create a new class for each one. It follows Python range semantics, with the lower value using a `_gte` test and the upper value using an `_lt` test. Here's an example of how I'm using it in one of my projects: list_filter = ('complete', ('chapters', makeRangeFieldListFilter([ (_('1'), 1, 2), (_('2 to 10'), 2, 10), (_('11 to 30'), 11, 30), (_('31 to 100'), 31, 100), (_('At least 100'), 100, None), ], nullable=True)), ('word_count', makeRangeFieldListFilter([ (_('Less than 1000'), None, 1000), (_('1K to 5K'), 1000, 5000), (_('5K to 10K'), 5000, 10000), (_('10K to 75K'), 10000, 75000), (_('75K to 150K'), 75000, 150000), (_('150K to 300K'), 150000, 300000), (_('At least 300K'), 300000, None), ], nullable=True)), ('derivatives_count', makeRangeFieldListFilter([ (_('None'), 0, 1), (_('1 to 5'), 1, 5), (_('5 to 50'), 5, 50), (_('50 to 1000'), 50, 1000), (_('At least 1000'), 1000, None), ])), 'pub_date', 'upd_date') It is based on code from `DateFieldListFilter` and `BooleanFieldListFilter` from `django.contrib.admin.filters`.

  • filter
  • django
  • admin
  • fieldlistfilter
Read More

Show template names in markup

Simple snippet to show the names of the templates on the page. It's a custom template loader that just prints out the name of the template at the start of the template. To set it up, just place it in a file, for example spy.py. Then edit settings.py and add this to the start of the tuple list for TEMPLATE_LOADERS. TEMPLATE_LOADERS = ( 'appname.spy.load_template_source', 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) This was useful for me because I'm starting to use a django project that's a big on the big side and I'm trying to do a theme for it. I'm not very familiar with their templates, so these visual cues will help instead of walking through the template code. Hope this is helpful for some one else too.

  • template
  • templates
  • loader
Read More

PatchModelForm - A ModelForm subclass with the semantics of the PATCH HTTP method

Use this class to partially update one or more fields of a model. Only the fields that are bound to the form via the "data" parameter in the constructor get updated. All automatically generated fields have their "required" attribute set to False. Example 1: from django.contrib.auth.models import User class PatchUserForm(PatchModelForm): class Meta: model = User user = User.objects.get(username='old_username') form = PatchUserForm(data={'username':'new_username'}, instance=user) form.is_valid() form.save() Example 2: from django.contrib.auth.models import User class PatchUserForm(PatchModelForm): class Meta: model = User user = User.objects.get(pk=35) form = PatchUserForm(data={'last_name':'Smith', 'is_staff': True}, instance=user) form.is_valid() form.save()

  • models
  • rest
  • update
  • patch
  • partial-update
Read More

yandex maps templatetag

https://github.com/coolchevy/django-yandexmaps django-yandexmaps ================= easy maps integration via yandex maps api Installation ============ 1. Add your YANDEXMAPS_API_KEY to settings.py http://api.yandex.ru/maps/form.xml/ 2. Add 'yandex_maps' in INSTALLED_APPS Usage ============ Template:: {% load yandexmaps_tags %} {% yandex_map_by_address object.get_address object.title 500,300 %} Demo ============ http://colorsound.com.ua/clubs/porter-pub-1/

  • template
  • django
  • templatetag
  • api
  • templatetags
  • yandex
  • maps
Read More

RelatedMixin for Details and Updates with Related Object Lists

Code for a RelatedMixin I whipped up, useful in instances where you wish to expose details of a single object, including a related group of owned objects, in the same view. Works well with Django's generic DetailView and UpdateView, or any subclass of SingleObjectMixin. It's a little cleaner than overriding get_context_data differently for every model you want to expose, uses `only('id')` on querysets it doesn't need anything but relational data from, and makes pulling ownership out of distantly related objects much easier. Supports simple nested hierarchies of models, ie: * View a company and all people belonging to it Detail(Company < People) * Edit a company and all computers belonging to its members Update(Company < People < Computers). Tested with non-generic One-To-Many and reverse object_sets only. Just provide an OrderedDict called `related_chain` in your DetailRelatedView that describes the progression of querysets to follow, in the format: model=Foo, relation_chain=OrderedDict([ ('foreign_key_from_foo_to_bar',Bar.objects.all()), ('foreign_key_from_baz_to_bar',Baz.objects.all()) ]) It also takes two optional attributes: context_list_name="baz_list" which provides an alias for the final related `object_list` (default=`related_list`), and keep_intermediaries=True which, if providing a list deeper than one relation, also passes any intermediary related lists into the context, named after the connecting foreign key, like `bar_list` (default=False).

  • mixin
  • model-filtering
  • class-based-generic-view
Read More

Debug SQL Query in Template

before this works, you'll need to satisfy all the criteria for getting debug information in your template context: Have 'django.core.context_processors.debug' in your TEMPLATE_CONTEXT_PROCESSORS setting (it was there in the default settings, last time I checked). Have your current IP in your INTERNAL_IPS setting. Use RequestContext when rendering the current template (if you're using a generic view, you're already using RequestContext). [Manuale Django](http://www.darioagliottone.it/django-guida/)

  • sql
  • template
  • debug
  • debugging
  • sql_queries
Read More

REMOVE IMAGEFIELD ATTACHMENT IN DJANGO

File cleanup callback used to emulate the old delete behavior using signals. Initially django deleted linked files when an object containing a File/ImageField was deleted. Usage: >>> from django.db.models.signals import post_delete >>> post_delete.connect(file_cleanup, sender=MyModel, dispatch_uid="mymodel.file_cleanup")

  • filefield
Read More

Unit Test Profiling for Django 1.3/1.4

The snippet is a modification of [snippet 1315](http://djangosnippets.org/snippets/1315/) to fit the needs for Django 1.3 and 1.4. You can follow the explanations and instructions there. To plot a nice and so useful call-graph with timings, call: $ gprof2dot -f pstats unittest.profile | dot -Tpng -o unittest.profile.graph.png where 'unittest.profile' is the test runners profile output defined in your settings.

  • profile
  • unittest
  • runtime
  • cprofile
Read More

Pagination Alphabetically compatible with paginator_class

This is just a modified version of a [previous snippet](http://djangosnippets.org/snippets/1364/) to make it work with unicode and with class-based ListView paginator_class To use it put this in your urls.py: `from youapp.fileyouchose import NamePaginator` `urlpatterns = patterns('',` `url(r'^example/(?P<page>[0-9]+)/$', ListView.as_view(model=myModel,template_name="mytemplate.html",paginator_class=NamePaginator,paginate_by=25), name="url_name"),` And then in your template something like this would work: {% if page_obj.has_other_pages %} <div class="row"> <div class="span12"> <div class="pagination"> <ul> {% if page_obj.has_previous %} <li><a href="{% url page page=page_obj.previous_page_number %}">Prev</a></li> {% else %} <li class="disabled"><a>Prev</a></li> {% endif %} {% for p in page_obj.paginator.pages %} <li {% if p == page_obj %}class="active"{% endif %}> <a href="{% url category_page page=p.number %}">{{ p }}</a> </li> {% endfor %} {% if page_obj.has_next %} <li><a href="{% url page page=page_obj.next_page_number %}">Next</a></li> {% else %} <li class="disabled"><a>Next</a></li> {% endif %} </ul> </div> </div> </div> {% endif %}

  • django
  • pagination
  • listview
Read More

Custom requests auth class for Tastypie API key authentication

In case you ever use [requests](http://python-requests.org/) (or [slumber](http://slumber.in/)) to do requests against a Tastypie API that requires API key authentication, this small custom auth class will help you. Use it like that (with requests): auth = TastypieApiKeyAuth('jezdez', '25fdd0d9d210acb78b5b845fe8284a3c93630252') response = requests.get('http://api.foo.bar/v1/spam/', auth=auth) or with slumber: auth = TastypieApiKeyAuth('jezdez', '25fdd0d9d210acb78b5b845fe8284a3c93630252') api = slumber.API("http://api.foo.bar/v1/", auth=auth) spam = api.spam().get()

  • api
  • auth
  • tastypie
Read More

Delete template fragment cache

Template: {% load cache %} {% cache 1800 posts blog.pk %} {# Show posts #} {% endcache %} Code: def view(request, pk): # Code blog = get_object_or_404(Blog, pk=pk) delete_template_fragment_cache('posts', blog.pk) # Code

  • template
  • cache
  • fragment
Read More

dropbox integration

This is a simple module for use with django to make a per user dropbox access simple Requirements: * standard django authentication * django sessions enabeled * dropbox python api >> easy_install dropbox To use this dropbox module you have to add the following configuration to your settings.py file `DROPBOX_SETTINGS = { 'app_key' : "insert key", 'app_secret' : "insert secret", 'type' : "app_folder", }` and of course to include it in INSTALLED_APPS `INSTALLED_APPS = ( ..., 'django_dropbox', )` to make a table to store personal access tokens for your users run >> python manage.py syncdb In your views you can import the dropbox_user_required decorator to mark views that should recive the named parameter dropbox_client ` from django_dropbox.decorator import dropbox_user_required @dropbox_user_required def myViewFunk(request, ..., dropbox_client): file = ... dropbox_client.put_file(file) `

  • dropbox
  • cloud-storage
Read More

3110 snippets posted so far.