Login

All snippets written in Python

Snippet List

Admin page without inlines dinamically

Sometimes the related objects needs that the main object exists in order to edit and save them properly. There are two main solutions: override the ModelAdmin.add_view() view or remove the inlines only from the add view page (and not from the change page). The former requires a lot of coding, the latter it's impossible without patching Django because the inlines are not dynamic. **This simple solution hides the inline formsets only from the add page, and not from the change page.** Adding an "if" structure it is possible to choose the inlines to use. Example use case: when a related inline model have to save a file to a path that needs the ID key of the main model, this solution prevent the user to use the related inline model until the model it's saved. Tested on Django-1.4, should work since Django-1.2.

  • admin
  • inlines
  • change_view
  • add_view
Read More

Allow separation of GET and POST implementations

Django does not have a clean, built-in mechanism to separate GET and POST implementations. This simple decorator provides this behavior. Django does provide an alternate way using class-based views, but defining class for each of your view functions may be an overkill. You can name the get and post functions anything you wish, but you need to make sure they are returned in the same order (get first and then post). Example usage: @formview def edit(request, id): form = EditForm(id, request.POST or None) def get(): return render(request, 'edit.html', {'form' : form}) def post(): if form.is_valid(): form.save(id) return redirect('list') return get, post

  • get
  • decorator
  • post
Read More

SELECT FOR UPDATE in Django < 1.4

SELECT FOR UPDATE, which does row-level locking in the database, was added by Django only in version 1.4. This snippet emulates that feature in older versions of Django. Tested in Django 1.2, but should work in newer versions as well. select_related is removed because it causes errors when used with RawQuerySet.

  • queryset
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

Digg-style pagination, and retain GET params

This snipplet is based on [Ryan Kanno's work](http://blog.localkinegrinds.com/2007/09/06/digg-style-pagination-in-django/) and [snipplet #2680](http://djangosnippets.org/snippets/2680/). The page numbers are basically composed by `pages_outside_trailing_range`, `page_range` and `pages_outside_leading_range`. The GET params in the request(except for `page` itself) are retained across different pages. This is important when you have an `order_by` param working inline.

  • pagination
Read More

Routing urls.py By Convention

No more entries in urls.py... This is the simple version of a central controller for an app that routes requests by names, thus keeping you from adding a line into urls.py for every, single, page. Assuming your app name is "account", add the following to your urls.py file: (r'^account/(?P<path>.*)\.dj(?P<urlparams>/.*)?$', 'account.views.route_request' ) The URL /account/mypage.dj will be routed directly to account.views.py -> process_request__mypage(request, parameters). You can read more about this on [my blog](http://warp.byu.edu/site/content/1100).

  • urls
  • routing
Read More

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

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

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

MultiSelectField with comma separated values (Field + FormField)

Daniel Roseman's snippet, updated will all fixes mentioned in the comments of the first version + some other things to make it work under Django 1.4. South, and dumpdata are working. There's an ugly int(....) at the validate function in order to cast each value as an integer before comparing it to default choices : I needed this, but if you're storing strings values, just remove the int(......) wrapper. ------------------------------------- Orginal readme Usually you want to store multiple choices as a manytomany link to another table. Sometimes however it is useful to store them in the model itself. This field implements a model field and an accompanying formfield to store multiple choices as a comma-separated list of values, using the normal CHOICES attribute. You'll need to set maxlength long enough to cope with the maximum number of choices, plus a comma for each. The normal get_FOO_display() method returns a comma-delimited string of the expanded values of the selected choices. The formfield takes an optional max_choices parameter to validate a maximum number of choices.

  • checkbox
  • multiple
  • forms
  • model
  • field
  • comma
Read More

2955 snippets posted so far.