Login

Top-rated snippets

Snippet List

Querying datetime aware objects in your local timezone

I have a model with a datetime field that I used as a timestamp. I’m in California’s timezone (“America/Los_Angeles”). The data is saved in UTC in MySQL (as confirmed by the ORM). I just want to do a query that looks like this: “give me all the information with day X’s timestamp” (24 hour period). But the timestamp is a datetime, not date. If you just do varname.date(), it’s still UTC’s date, not your local timezone’s date. Here’s what I did: 1. First construct the start and end time period covering the 24 hour period of that day you want 2. Make it an “aware” (not naive) datetime 3. Filter for the __range

  • datetime
  • timezone
  • queryset
  • utc
  • local
  • datetimefield
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

django ajax_view decorator

All credit goes to Peter Coles. [http://mrcoles.com/blog/decorator-django-ajax-views/#c281](http://mrcoles.com/blog/decorator-django-ajax-views/#c281) I slightly modified the original code to work without passing parameters to decorator. I will delete this post if anyone does not want this snippet to be posted.

  • ajax
  • ajax view decorator
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

DisableableSelectWidget

A Select widget that allows choices to be disabled. Specify `disabled_choices` to indicate which choices should be present in the list, but disabled. A possible use case for this is a form that displays data that can be edited by privileged user's but only viewed by others.

  • form
  • select
  • widget
Read More

Django mediagenerator folder bundler

This code will put an entire folder into your media bundle - instead of having to write out every file in a given folder: *It assumes your static root is a absolute directory* **Usage** MEDIA_BUNDLES = ( ('init.js', 'coffeescript/init.coffee', ), bundle_builder('libraries.js', 'javascript/vendor'), bundle_builder('main.js', 'coffeescript', exclude=['init.js',]), bundle_builder('templates.js', 'eco'), ) **Notes** You may wish to use [cache_utils](http://pypi.python.org/pypi/django-cache-utils) or similar to avoid crawling the filesystem every time the site loads

  • django
  • wildcard
  • django-mediagenerator
  • mediagenerator
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

Drupal password hasher for migration

This BasePasswordHasher allows the easy migration of passwords from Drupal to Django 1.4. Drupal stores its passwords using a SHA512 hash, but with some iterations and postprocessing. This snippet allows you to migrate the username and passwords over seamlessly- the only necessary change is truncating the first character of each password hash (since Django 1.4 stores each password as algorithm$hash). Note that this snippet *requires* Django 1.4, but there is no option for that snippet in the list. Provided as a github gist [here](https://gist.github.com/2344345).

  • migration
  • password
  • hash
  • drupal
Read More

Apache X-sendfile with permissions checking

This allows the mod_xsendfile module for Apache safely serving private files. Django take cake about processing and permissions checking, Apache server requested files. Installation of mod_xsendfile: $ tar -xzvf mod_xsendfile-0.12.tar.gz $ /usr/sbin/apxs -c mod_xsendfile-0.12/mod_xsendfile.c $ ld -Bshareable -o mod_xsendfile-0.12/mod_xsendfile.so mod_xsendfile-0.12/mod_xsendfile.o Copy mod_xsendfile.so to your local Apache modules folder. Modify httpd.conf to load an enable the module: LoadModule xsendfile_module modules/mod_xsendfile.so Add to virtual host container: <Virtual ...:80> XSendFile On XSendFilePath /home/django_projects/mysite/media/ </Virtual>

  • http
  • media
  • static
  • xsendfile
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

Database template loader

This snippet provides getting templates from the model in database. We work with templates as usual (using as a template name value of the field **"slug"**). You can do your own application without "TemplateTypes" model - it's added for ability to filter templates. You can use choices or remove "template_type" field and "TemplateTypes" model at all. For ease of editing, you can connect all this to the admin interface, adding to the field "template_body" widget with syntax highlighting (I used [CodeMirror](http://codemirror.net/)).

  • templates
  • template loader
Read More

3110 snippets posted so far.