Login

Most bookmarked snippets

Snippet List

Download images as png or pdf

This is an example of how I am providing downloads of dynamic images in either PNG or PDF formats. The PDF format requires ImageMagick's `convert`, and temporary disk space to save the intermediary image. If anyone knows a way to avoid writing to disk, I'd be happy to include it here. I realize there may be uses where it isn't necessary to use the PIL Image class if the image is already stored as a file. This is used for downloading dynamic images without saving them to disk (unless pdf format is used).

  • pdf
  • png
  • custom-response
  • subprocess
Read More

Django Using Stored Procedure

Here is an clean example of using stored procedure using django. It sounds pretty weird "stored procedures in django" but for legacy database system we still need a clean approach to implement stored procedures using django. In this example, I've implemented logic inside models.py by creating a dummy class, i.e a django table (which is comparable to package in your database) and inside this package/class i added stored procedure wrappers. I tested it with boulder-oracle-sprint branch, there is minor issues with LazyDate in db/backend/oracle/base.py but it still working after minor edits in base.py. It worked absolutely fine with MySQL and MSSQL. View is pretty straight forward. Dont forget to create form.html as template and in body just put {{ form }}

  • django
  • stored
  • procedures
  • oracle
  • mysql
Read More

Setting distinction between development and public server

If your code is under source control and you develop locally and then publish that globally, you might need to modify the settings file after each update to ensure the system paths and database settings are correct. This simple solution helps to distinguish development server from the public server. And you won't need to care about modifying files on the public server anymore. Create a file called `dev_environment.py` in your `site-packages` directory of the development server only (do not put it under source control). Then use the following lines in the beginning of your files, you want to check whether you are in the development environment. try: from dev_environment import * except: is_dev_environment = False Then for example, you can set the database settings according the environment: if is_dev_environment: DATABASE_NAME = "test" DATABASE_USER = "root" DATABASE_PASSWORD = "" else: DATABASE_NAME = "publicproject" DATABASE_USER = "projectuser" DATABASE_PASSWORD = "ahl3379ljkasd"

  • development
  • public
Read More

Using the built-in slugify filter outside a template

This is just a very short (and mostly useless on it's own) example of how the built in slugify filter can be used in a Python script to generate slugs. It was pulled from a script I've written to pull in items from Upcoming.org's API. I post it because "sunturi" posted [Snippet #29](http://www.djangosnippets.org/snippets/29/), which duplicates the functionality of the built-in slugify filter. In the comments of that snippet, santuri (and others) seem to believe that template filters can only be used within templates. This is incorrect, and I think it's important people understand they can be used elsewhere. sunturi's snippet does remove prepositions from values before slugifying them, so if you need that, his code will work work. But if all you need is slugification, the built-in slugify filter will work fine -- in a Python script, as well as in a template.

  • template
  • filter
  • django
  • slug
  • built-in
Read More

assign fields dynamically in newforms

DynamicFieldSnippetForm demonstrates how to dynamically assign fields in newforms. 1. weight is a required static field 2. height is an optional dynamic field This example uses `request_height` as an optional keyword argument to declare whether the `height` field should be added to the form, but it's just there for demonstration purposes. If you decide to use a keyword argument in your code, be sure to pop it off (as demonstrated in the code) or you'll get an *unexpected keyword argument* error.

  • newforms
  • dynamic
  • fields
Read More

Export queryset to Excel workbook

How to use =========== Save the snippet to a file utils.py, and add the following view to your Django app: from django.http import HttpResponse from .utils import queryset_to_workbook def download_workbook(request): queryset = User.objects.all() columns = ( 'first_name', 'last_name', 'email', 'is_staff', 'groups') workbook = queryset_to_workbook(queryset, columns) response = HttpResponse(mimetype='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="export.xls"' workbook.save(response) return response Note: you can use dotted notation (`'foreign_key.foreign_key.field'`) in the columns parameter to access fields that are accessible through the objects returned by the queryset (in that case you probably want to use `select_related` with your queryset).

  • export
  • queryset
  • xlwt
Read More

Model Mixin to Save Only Changed Fields

**[Improved and Released as Save The Change.](https://github.com/karanlyons/django-save-the-change)** Django 1.5 added the `update_fields` `kwarg` to `Model.save()`, which allows the developer to specify that only certain fields should actually be committed to the database. However, Django provides no way to automatically commit only changed fields if they're not specified. This mixin keeps track of which fields have changed from their value in the database, and automatically applies `update_fields` to update only those fields.

  • model
  • save
  • mixin
  • class
  • automatic
  • update_fields
Read More

Keeping filter states after edits (Django 1.4)

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. This solution doesn't require changes to template code...this is completely self contained within your own admin.py files. The solution presented here is a revision of a previous patch, which has been modified for Django 1.4. The Django 1.3 version exists at: http://djangosnippets.org/snippets/2531/ From chronosllc: 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.

  • filter
  • admin
  • change_list
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

3110 snippets posted so far.