Login

All snippets written in Python

2956 snippets

Snippet List

Name Capitalize Filter

This is to be used as a template filter. See [django documentation](http://www.djangoproject.com/documentation/templates_python/#writing-custom-template-filters) for adding custom filters. Example of use: name = "bart simpson" `{{ name|cap }}` will convert 'name' to "Bart Simpson" It works on space-separated names, as well as the following: * converts "mcfly" to "McFly"; * converts "o'neill" to "O'Neill"; * converts "barker-bradley" to "Barker-Bradley"

  • names
  • template-filters
  • capitalize
Read More

RequestStack middleware

This is some very simple middleware that keeps track of the last 3 succesful requests for each visitor. This can be useful if you want to redirect the visitor to a previous path without relying on a hidden field in a form, or if you simply want to check if a visitor has recently visited a certain path. Note that this relies on the session framework and visitors actually accepting cookies. This can be easily modified to hold more requests if you have a need for it.

  • middleware
Read More

Middleware to detect visitors who arrived from a search engine

Sometimes it's nice to know if your visitors came from a search engine such as Google or Yahoo. I use this as a component in determining the popularity of blog articles for search keywords, so I know which articles to automatically feature or suggest. Maybe you'd like to use it to highlight the visitor's search terms on the page. This isn't actually middleware in the sense that it defines any of the middleware interfaces. It's intended to be the base for a middleware method that you write, depending on what you want to happen when you detect that the visitor came from a search engine. In the example `process_view` method, I detect when the request is going to use the `object_detail` view and log the search query for that object in the database.

  • middleware
  • search-engine
  • referrer
Read More

filter dates to user profile's timezone

I have users in many timezones and I let them set their preferred display timezone in their user profile as a string (validated aginst the pytz valid timezones). This is a filter that takes a datetime as input and as an argument the user to figure out the timezone from. It requires that there is a user profile model with a 'timezone' field. If a specific user does not have a user profile we fall back on the settings.TIME_ZONE. If the datetime is naieve then we again fallback on the settings.TIME_ZONE. It requires the 'pytz' module: [http://pytz.sourceforge.net/](http://pytz.sourceforge.net/) Use: `{{ post.created|user_tz:user|date:"D, M j, Y H:i" }}` The example is assuming a context in which the 'user' variable refers to a User object.

  • filter
  • timezone
  • userprofile
Read More

roman numbers template filter

dirt and simple template filter to convert a number to its roman value. taken from dive into python http://www.diveintopython.org/unit_testing/stage_5.html

  • template
  • filter
  • filters
  • roman
  • numbers
Read More

Currency Fields with newforms

The newforms package allows you to simply add new field types to your forms. This snippet shows the addition of a new type of field, to make sure the user enters sensible currency values (either with no decimal, or two-decimal places), and a custom widget to make sure that the value is displayed correctly when the user sees the form. The CurrencyInput widget simply tries to display the current value in floating point 2-decimal places format (and gives up if it can't). The CurrencyField makes sure that the input value matches a regular expression, and when it is asked to clean the value it converts it to a float. The regex here limits the amount to 99,999.99 or less. This is within the bounds of accuracy of python's float value. If you want to use truly huge values for the amount, then you'll face problems with the floating point not being able to represent the values you enter, and so the conversion to floating point in the field will fail. In this case it would be better to use python longs, and used a fixed point interpretation.

  • newforms
  • validation
  • currency
  • form
  • widgets
Read More

Import mail into a Django model

A mildly crufty script to slurp mail from an mbox into a Django model. I use a variant of this script to pull the contents of my scammy-spam mbox into the database displayed at <http://purportal.com/spam/>

  • email
  • faceless
  • utility
Read More
Author: pbx
  • 4
  • 11

use oldforms validators in newforms forms

Using the `run_oldforms_validators` function, you can run oldforms validators in your newforms `clean_XXX` methods. Usage example: class PasswordForm(forms.Form): password = forms.CharField(widget=forms.PasswordInput()) def clean_password(self): validator_list = [ isStrongPassword, isValidLength, SomeValidators( num_required=3, validator_list=[hasLower, hasUpper, hasNumeric, hasSpecial], error_message="Password must contain at least 3 of: lowercase, uppercase, numeric, and/or special characters." ) ] run_oldforms_validators('password', self, validator_list) return self.clean_data['password'] Above, `isStrongPassword`, `isValidLength`, etc. are oldforms validators. If you are interested in seeing the implementation of `isStrongPassword`, please see my [Using CrackLib to require stronger passwords](http://gdub.wordpress.com/2006/08/26/using-cracklib-to-require-stronger-passwords/) blog post.

  • newforms
  • validators
  • oldforms
Read More

MediaWiki Markup

This is a copy paste job of mediawiki's syntax parser built in Python. You'll probably have to edit it to fit your needs MediaWiki-style markup parse(text) -- returns safe-html from wiki markup code based off of mediawiki

  • markup
  • mediawiki
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

SQL Log Middleware

This middleware will add a log of the SQL queries executed at the bottom of every page. You can (should) use BeautifulSoup to place this in a specific location. Note: If you serve non-html content, it would be wise to do a mimetype check.

  • sql
  • middleware
  • log
Read More

Function to create resized versions of an image from a URL and saving it to a local path

This is a really useful function I used to create the resized preview images you can see on the [homepage of my site](http://www.obeattie.com/). Basically, it takes the original URL of an image on the internet, creates a resized version of that image by fitting it into the constraints specified (doesn't distort the image), and saves it to the MEDIA_ROOT with the filename you specify. For example, I use this by passing it the URL of a Flickr Image and letting it resize it to the required size, and then saving it to a local path. It then returns the local path to the image, should you need it. I however just construct a relative URL from the image_name and save that to the database. This way, it's easy to display this image. Hope it's useful!

  • image
  • pil
  • thumbnail
  • resize
Read More

ForeignKey dropdown selector

Most of the time when you want a dropdown selector based on a ForeignKey, you'll want to use [snippet #26](http://www.djangosnippets.org/snippets/26/) Here's an alternative approach, perhaps useful when you want to define choices once and reuse it in different views without overriding Form `__init__`.

  • dynamic
  • foreignkey
  • dropdown
  • choices
  • property
Read More