Login

All snippets written in Python

Snippet List

LinkSleeve comment moderation

This is an extension to ubernostrum's [comment-utils](http://code.google.com/p/django-comment-utils/) that performs comment moderation based on LinkSleeve check result. It requires original comment-utils package.

  • akismet
  • comment
  • moderation
  • linksleeve
Read More

Django Registration without username

A simple adaptation of RegistrationFormUniqueEmail from django-registration http://code.google.com/p/django-registration to allow users to register without using a username. This works great with the code from this comment: http://www.djangosnippets.org/snippets/74/#c195 to allow users to completely eliminate the need for a username.

  • registration
  • auth
Read More

Set test cookie unless logged in

This allows you to use a quick login forms outside of the django.contrib.auth.views.login view, the cookie will be deleted once you login.

  • middleware
  • cookie
  • login
Read More

PHP's number_format like template filter

This filter allows you to format numbers like PHP's [number_format](http://php.net/number_format) function. If `var` equals 1234.567`{{ var|number_format:2 }}` produces 1,234.56. Because Django's template filters support just 1 argument you'll have to adjust the argument's default values by hand until [#1199](http://code.djangoproject.com/ticket/1199) is fixed.

  • filter
  • number_format
Read More

Clear session data on login and logout

This was born as a result of the fact that session data is shared across logins on a single browser. If you login as user1 and session data is stored, then login as user2 the same session data will be available to your application. Please see the ticket who's validity is at this point in question. Some feel that this is normal behavior. http://code.djangoproject.com/ticket/6941 I use this code in conjunction with http://code.google.com/p/django-registration/ Place this code in registration.__init__ and change registration.urls to have login and logout route to the new alternate versions alt_login, alt_logout. I have only been using Python and Django for a couple months now so I hope that this implementation is not too terrible. It works for me. Enjoy.

  • session
  • login
  • logout
  • delete
  • clear
  • sessions
Read More

Soft-wrap long lines

This filter naively parses HTML content, and inserts <wbr/> tags in lines with unbroken strings longer than max_line_length characters. It leaves content inside tags alone, so that things like urls are unaltered. XHTML entities are treated as atomic, and whitespace is determined with a regex. It assumes well formed HTML.

  • filter
  • line-break
  • wbr
  • softwrap
Read More

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

2956 snippets posted so far.