Login

All snippets written in Python

Snippet List

Url filter middleware

How to config it ------------------ You can treat it as a micro url filter framework. Before you using it, you should setup some options about it. The option entry shoud be like this: FILTERS = ( (r'^user/(?P<user_id>\d+)/', 'apps.users.filter.check_valid_user'), ) FILTERS should be a list or tuple with two elements tuple item. The format should be like: (url_patterns, function) And url_patterns could be a single regex expression or a list/tuple regex expressions, So you can set multi regex expression in it. And the regulation is just like url dispatch, as above example, the url pattern is: r'^user/(?P<user_id>\d+)/' So you can see, you can set parameter name `user_id`, then it'll be passed to the function behind. Function can be a string format, just like above example, and it can be also a real function object. It'll only impact request. How to write filter function ------------------------------- According above example, I define a url pattern, and what to check if the user is a valid user, and if the user is visiting his own urls, so the filter function could be: from django.contrib.auth.models import User from utils.common import render_template def check_valid_user(request, user_id): if request.user.is_anonymous(): return render_template(request, 'users/user_login.html', {'next':'%s' % request.path}) try: person = User.objects.get(pk=int(user_id)) except User.DoesNotExist: return render_template(request, 'error.html', {'message':_("User ID (%s) is not existed!") % user_id}) if person.id != request.user.id: return render_template(request, 'error.html', {'message':_('You have no right to view the page!')}) I think the code is very clear. And you can use it filtermiddleware to do like user authentication check, and other checking for url. BTW, render_template is comes from [Snippets #4](http://www.djangosnippets.org/snippets/4/)

  • middleware
  • filter
  • url
Read More

mask_email filter

Mask an email address by removing most of the first portion and replacing it with "..." For example. If you have a variable in your template context named `email_address `, and its value is "[email protected]" {{ email_address|mask_email }} will render as: [email protected] If the part preceding @domain.com is shorter than 5 characters, only the first letter will be used, followed by "...". So if we have "[email protected]" {{ email_address|mask_email }} will render as: [email protected]

  • filters
  • email
Read More

Browser Verification

A page we used on Curse to stop users who are new, who are using old browsers (ones who usually have extreme issues with CSS handling) and recommend they update. Can easily be modified to suit your needs.

  • middleware
  • browsers
  • validation
Read More

Whore links

Finds links from a body of html so you can display them elsewhere.

  • beautiful-soup
  • links
Read More

Use email addresses for user name

Django's built in authentication system requires the username to be alpha-numeric only. Therefore, email addresses are invalid. However, in many cases, you would like to use an email address as the username. This snippet allows you to do so. It has the added benefit that if you want to continue using the regular username format, you can do that too. It's the best of both worlds! To make sure propoer credit is given, this code is modified from a django group posting from Vasily Sulatskov. To use this file, save it in your project as something like: email-auth.py Then, add the following lines to your settings.py file: AUTHENTICATION_BACKENDS = ( 'yourproject.email-auth.EmailBackend', ) You can see a full implementation [here] (http://www.satchmoproject.com/trac/browser/satchmo/trunk/satchmo)

  • authentication
Read More

Paginator Tag

Piggybacks on the pagination-related template context variables provided by the `object_list` generic view, adding extra context variables for use in displaying links for a given number of pages adjacent to the current page and determining if the first and last pages are included in the displayed links. Also makes it easy to implement consistent paging all over your site by implementing your pagination controls in a single place - paginator.html. Optionally accepts a single argument to specify the number of page links adjacent to the current page to be displayed. Usage: `{% paginator %}` `{% paginator 5 %}`

  • template
  • tag
  • pagination
Read More

Format transition middleware

Note: This is a testing middleware. This snippets may be changed frequently later. What's it ----------- Sometimes I thought thow to easy the output data into another format, except html format. One way, you can use decorator, just like: @render_template(template='xxx') def viewfunc(request,...): And the output data of viewfunc should be pure data. And if want to output json format, you should change the decorator to: @json_response def viewfunc(request,...): I think it's not difficult. But if we can make it easier? Of cause, using middleware. So you can see the code of `process_response`, it'll judge the response object first, if it's an instance of HttpResponse, then directly return it. If it's not, then get the format of requst, if it's `json` format, then use json_response() to render the result. How to setup `request.format`? In `process_request` you and see, if the `request.REQUEST` has a `format` (you can setup it in settings.py with FORMAT_STRING option), then the `request.format` will be set as it. If there is not a such key, then the default will be `json`. So in your view code, you can just return a python variable, this middleware will automatically render this python variable into json format data and return. For 0.2 it support xml-rpc. But it's very different from common implementation. For server url, you just need put the same url as the normal url, for example: http://localhost:8000/booklist/ajax_list/?format=xmlrpc Notice that the format is 'xmlrpc'. A text client program is: from xmlrpclib import ServerProxy server = ServerProxy("http://localhost:8000/booklist/ajax_list/?format=xmlrpc", verbose=True) print server.booklist({'name':'limodou'}) And the method 'booklist' of server is useless, because the url has include the really view function, so you can use any name after `server`. And for parameters of the method, you should use a dict, and this dict will automatically convert into request.POST item. For above example, `{'name':'limodou'}`, you can visit it via `request.POST['name']` . For `html` format, you can register a `format_processor` callable object in `request` object. And middleware will use this callable object if the format is `html`. Intall --------- Because the view function may return non-HttpResponse object, so this middleware should be installed at the end of MIDDLEWARE_CLASSES sections, so that the `process_response` of this middleware can be invoked at the first time before others middlewares. And I also think this mechanism can be extended later, for example support xml-rpc, template render later, etc, but I have not implemented them, just a thought. Options --------- FORMAT_STRING used for specify the key name of format variable pair in QUERY_STRING or POST data, if you don't set it in settings.py, default is 'format'. DEFAYLT_FORMAT used for default format, if you don't set it in settings.py, default is 'json'. Reference ----------- Snippets 8 [ajax protocol for data](http://www.djangosnippets.org/snippets/8/) for json_response

  • middleware
  • format
  • json
Read More

Simple profile middleware

Intall -------- In your settings.py, set it in MIDDLEWARE_CLASSES. Default all the profile files will be save in ./profile folder(if there is no this directory, it'll automatically create one), and you can set a PROFILE_DATA_DIR option in settings.py, so that the profile files can be saved in this folder. How does it works ------------------- Record every request in a profile file. As you can see in the code: profname = "%s.prof" % (request.path.strip("/").replace('/', '.')) so if you request an url multi-times, only the last request will be saved, because previous profile files will be overriden. And you can find a commentted line, it'll save each request in different file according the time, so if you like that you can change the code. # profname = "%s.%.3f.prof" % (request.path.strip("/").replace('/', '.'), time.time()) and if you want to see the output, you can run below code, but you should change the filename value: import hotshot, hotshot.stats stats = hotshot.stats.load(filename) #stats.strip_dirs() #stats.sort_stats('time', 'calls') stats.print_stats()

  • middleware
  • profile
Read More

Using Templates to Send E-Mails

This is a basic example for sending an email to a user (in this case, when they've signed up at a website) using the Django template framework. It's really quite simple - we're just using a plain text template instead of HTML, and using the output of the template's 'render()' method as the message body. Of course, in your project you won't blindly use data from request.POST! This example was first posted on [my blog at rossp.org](http://www.rossp.org/blog/2006/jul/11/sending-e-mails-templates/)

  • templates
  • email
Read More

2955 snippets posted so far.