Login

All snippets

Snippet List

Upload progress handler using cache framework

Ticket [#2070](http://code.djangoproject.com/ticket/2070) allows you to create your own file upload handlers. Here's an example handler that tracks a file's upload so you might display a progress meter after form submission. The snippet has two parts, the upload handler which tracks progress, and an upload_progress view used to report back to the browser. The upload handler uses [django's cache framework](http://www.djangoproject.com/documentation/cache/#the-low-level-cache-api) to store the data, which can then be retrieved by the view to send back to the browser. Note: Your form's http post request must have a query parameter (X-Progress-ID) sent along with it, which should contain a unique key to identify the upload. That key will also be sent with your ajax requests to the upload_progress view to retrieve the progress data. Setup: place the UploadProgressCachedHandler anywhere you like on the python path, and add to your settings.py: from django.conf import global_settings FILE_UPLOAD_HANDLERS = ('path.to.UploadProgressCachedHandler', ) + \ global_settings.FILE_UPLOAD_HANDLERS Set up the upload_progress view in any of your apps along with a corresponding entry in your urlconf. Here's some javascript example code to make the ajax requests and display the progress meter: <http://www.djangosnippets.org/snippets/679/> .

  • ajax
  • upload
  • progress
Read More

JSON-compatible query filter specification

This function is designed to make it easier to specify client-side query filtering options using JSON. Django has a great set of query operators as part of its database API. However, there's no way I know of to specify them in a way that's serializable, which means they can't be created on the client side or stored. `build_query_filter_from_spec()` is a function that solves this problem by describing query filters using a vaguely LISP-like syntax. Query filters consist of lists with the filter operator name first, and arguments following. Complicated query filters can be composed by nesting descriptions. Read the doc string for more information. To use this function in an AJAX application, construct a filter description in JavaScript on the client, serialize it to JSON, and send it over the wire using POST. On the server side, do something like: > `from django.utils import simplejson` > `filterString = request.POST.get('filter', '[]')` > `filterSpec = simplejson.loads(filterString)` > `q = build_query_filter_from_spec(filterSpec)` > `result = Thing.objects.filter(q)` You could also use this technique to serialize/marshall a query and store it in a database.

  • filter
  • ajax
  • json
  • database
  • query
Read More

PK->objects in view signature

Let's suppose you have a view that fetches an object and renders a template with it. def show_blog_post(request, post_id): post = Post.objects.get(pk=int(post_id)) return render_to_response("show_post.html", dict(post=post)) That's all well and good. This decorator just lets you move one statement into what is essentially a declaration at the top of the function: "this is a view, that gets passed a primary-key ID, which I want to get the Post object for." @sigtransform([Post, int]) def show_blog_post(request, post): # post is actually the Post instance now! return render_to_response("show_post.html", dict(post=post)) If you want to leave an argument alone, pass None as that positional argument (excluding `request`.) @sigtransform(None, [MyModel, str]): def show_mymodel_stuff(request, leave_me_alone, model_obj): # ...etc... Internally, this just calls get_object_or_404 with the pk kwarg, which means it's not limited to integer keys. However, Model.objects.get requires that the pk arg be of the correct type, hence why the arguments are 2-element lists or tuples: the first is the actual model, the second is what cleaner function to apply to the passed in argument.

  • decorator
Read More

HTTP method_required Decorator

Edit: As James pointed out, `django.views.decorators.http` already provides stuff for this. Use that instead. Old description: Should be pretty straightforward; you give it the method you can accept, it returns 405's for other methods. EG, `@method_required("POST")` at the top of your view.

  • http
  • decorator
Read More

Paginator TemplateTag

**Paginator TemplateTag** TemplateTag to use the new Paginator class directly from a template. The paginate template tags take the following options: 1. list or queryset to paginate 2. number of pages 3. [optionaly] name of the Paginator.Page instance; prefixed by keyword 'as' 4. [optionaly] name of the http parameter used for paging; prefixed by keyword 'using' If you want to specify the parameter name with the keyword 'using' you must use the 'as' keyword as well. The default name of the paging variable is "page" and the paginator (the class that knows about all the pages is set in the context as "page_set". This follows the naming scheme of the ORM mapper for relational objects where "_set" is appended behind the variable name. Usage, put the following in your template: {% load paginate %} {% get_blog_posts blog_category as posts %} {% paginate posts 10 as page using page %} <ul> {% for post in page.object_list %} <li>{{ post.title }}</li> {% endfor %} </ul> <div> {% if page.has_previous %} <a href="?page={{ page.previous_page_number }}">previous</a> {% endif %} <i>{{ page.number }} of {{ page_set.num_pages }}</i> {% if page.has_next %} <a href="?page={{ page.next_page_number }}">next</a> {% endif %} </div> The templatetag requires the request object to be present in the template context. This means that you need 'django.core.context_processors.request' added to settings.TEMPLATE_CONTEXT_PROCESSORS list or otherwise make sure that the templatetag can access the request object. Comments are appreciated.

  • templatetag
  • pagination
  • paginator
Read More

A action decorator for URLs

This decorator handle a extra "action" parameter from an url and call this desired action in the provided views module. Example: from posts import views urlpatterns = patterns('posts.views', ... url(r'^(?P<id>\d+)/(?P<action>delete|publish|edit)/$', action(views), name="posts-action"), ... ) In templates: {% url posts-action id=post.id,action="delete" %}

  • rest
  • url
  • decorator
  • action
  • crud
Read More

Control FCGI processes through management

Add fcgi to settings.INSTALLED_APPS then you can start and stop FCGI through manage.py >python manage.py startfcgi >python manage.py stopfcgi In settings define runfcgi arguments using **FCGI_*** in settings For example: >FCGI_SOCKET='/var/tmp/project.sock' >FCGI_PIDFILE='/var/run/project.pid' One of **FCGI_SOCKET** or **FCGI_HOST**/**FCGI_PORT** will need to be defined, but if you forget they will error out. **FCGI_PIDFILE** is required to be defined to allow the process to be terminated.

  • management
  • fcgi
Read More

Twin column model admin index

**Problem:** A large project has lots of apps, so naturally you want a twin column admin interface, with the history out beyond those two columns... **Solution:** Involved editing the admin/index.html template, a simple modification to the adminapplist template tag, and a flag placed in each models.py for models you want in column two. **Instructions:** 1. Create the app templates/admin/index.html file by copying and pasting the provided code. 2. Copy django/contrib/admin/templatetags/adminapplist.py to your app/templatetags directory as column_adminapplist.py and edit as shown in the provided code. 3. add a \_admin\_index\_column = 2 near the top of each models.py file for each one you want to be on the right hand side.

  • admin
  • admin-panel
Read More

Restrict Flatpage To Group

Simple little flatpage wrapper view that lets you easily block off certain areas of flatpages to only a certain user group. Allows superuser in as well.

  • flatpages
  • groups
  • restricted
Read More

Choices datatype for model

This class will automatically create a django choices tuple like this: STATUS_CHOICES = django_choices(Draft=1, Public=2, Closed=3) Additionally, it includes a method that converts the choices tuple to a dictionary. Like this: STATUS = STATUS_CHOICES.to_dict() Those types can come in handy when you need to use those magic values in your code. Best done within the model once so everyone can use it. Code based on: http://www.djangosnippets.org/snippets/455/. By the way, if you want to just have the method without having to convert to the newer syntax.. it's backward compatible. Just add django_choices in front of the first paren for your choices tuple.

  • choices
  • model
Read More

Django and Twill

Django's test client is very limited when it comes to testing complex interactions e.g. forms with hidden or persisted values etc. Twill excels in this area, and thankfully it is very easy to integrate it. * Use `twill_setup` in your `TestCaseSubClass.setUp()` method * Use `twill_teardown` in `TestCaseSubClass.tearDown()` method * In a test, use something like `make_twill_url()` to generate URLs that will work for twill. * Use `twill.commands.go()` etc. to control twill, or use `twill.execute_string()` or `twill.execute_script()`. * Add `twill.set_output(StringIO())` to suppress twill output * If you want to write half the test, then use twill interactively to write the rest as a twill script, use the example in `unfinished_test()` Twill will raise exceptions if commands fail. This means you will get 'E' for error, rather than 'F' for fail in the test output. If necessary, it wouldn't be hard to wrap the twill commands to flag failure with TestCase.assert_ There are, of course, more advanced ways of using these functions (e.g. a mixin that does the setup/teardown for you), but the basic functions needed are here. See also: * [Twill](http://twill.idyll.org/) * [Twill Python API](http://twill.idyll.org/python-api.html)

  • testing
  • tests
  • twill
Read More

FormMail Clone

A quickie clone of good old fashion [Formmail.pl](http://www.scriptarchive.com/formmail.html) any form that is a subclass of FormMail will have its conents emailed to all staff members on the site.

  • newforms
  • email
  • formmail
Read More

3110 snippets posted so far.