Login

Most bookmarked snippets

Snippet List

shortcut for saving newforms to model

I come up with this short cut of saving data from newforms to a model, for newforms that contains attributes from several models or some attributes that doesn't found in a model attributes

  • newforms
  • model
Read More

Never cache a group of URLs

This is a special URL patterns replacement that prevents caching of any URL listed within it. We needed this in Review Board to prevent the JSON API function results from being cached in Internet Explorer.

  • urls
  • cache
  • url
  • patterns
Read More

Django & cache headers

This takes advantage of a recently added feature to django, being able to give it real functions as the view instead of having it be a string that is has to look up itself. It takes advantage of how decorators work and how `cache_control` works, normally you'd do something like this: @cache_control(private=True, public=False) def view_stuff(request): # ... return response Which is equal to doing `view_stuff = cache_control(private=True, public=False)(view_stuff)` after definition. `cache_control` is a function factory, more or less, which we use to our advantage.

  • cache
  • decorators
Read More

Validation for 'unique' and 'unique_together' constraints (different version)

This is a slightly different and extendend version of this snippet: http://www.djangosnippets.org/snippets/260/ Unique constraints for single fields are validated in a clean_FIELD, instead of globally in the form's clean() method, so that the error messages are correctly assigned to each field. Additionally, you can specify mappings for unique_together constraints to assign those error messages to a specific field as well (instead of having them in non_field_errors(), where they would normally be.

  • newforms
  • forms
  • validation
  • unique_together
  • unique
  • constraints
Read More

nofollow filter

This filter add extra attribute **rel="nofollow"** to any "<a ..." element in the value, which does not contain it already. I use this to filter comments text in my blog.

  • filter
Read More

Integrating Django with ToofPy

[ToofPy](http://pyds.muensterland.org/wiki/toolserver.html) is a python server that supports WSGI so you can integrate Django with it via the WSGI handler. There is already some default Django integration in the source, but it looked really hacked up with many `if hasdjango:` lines all over the place and hardcoded URLs. A really simple solution is to create a Tool for wrapping around Django. That is what the above file does. So I removed most of the hardcoded django lines and created the tool above. ToofPy dynamically loads tools based on paths on the filesystem, so you'll need to put the file above in the WSGI folder path. Or, if you want to pre-integrate, import the file in the _initops function of WSGIMainTool just after the code to scan the directory.

  • django
  • python
  • toofpy
  • toolserver-for-python
Read More

Table

This is rough code that will allow you to create a table using a sequence. It is based on the for loop tag in django template. It works basically the same except that certain variables are set based on what cell is being rendered. The tag itself does not output any html at all. This allows for simple code and very flexible creation of nice tables/grids. Enjoy

  • table
  • grid
Read More

Send information mails to related staff members.

You can use this method to send information mails to the related staff members about section specific site activity. All users which explicitly permitted to 'change' given object will be informed about activity. If you defined get_absolute_url in your model then you can simply use it like this; ` obj=form.save() mail2perm(obj) ` Or you can define your custom urls ; ` from util.mail2perm import mail2perm,domain reply=get_object_or_404(Reply,user=request.user,pk=id) mail2perm(reply,url='http://%s/admin/support/show/?id=%s'%(domain,reply.id)) `

  • mail
  • permission
Read More

Humanize lists of strings in templates

A simple template filter for taking a list and humanizing it, converting: `["foo", "bar"]` to `"foo and bar"` `["foo", "bar", "baz"]` to `"foo, bar and baz"` `["foo", "bar", "baz", "42"]` to `"foo, bar, baz and 42"`

  • filter
  • lists
  • filters
  • humanize
Read More

QEmpty

Q() value in Django is identity for & operation: Q() & foo & bar & ... == foo & bar & ... QEmpty() is complimentary identity for | operation: QEmpty() | foo | bar | ... == foo | bar | ... QEmpty() itself returns empty queryset. Handy for complex query generation.

  • q
  • query
Read More

Detect blog platform

Detect blog platform. As we all known, there are so many blog platform in the wild, e.g. Blogger.com, WordPress, LiveJournal, Movable Type etc. This little snippet could guess the blog platform according a url. Dependency: 1. pycurl 2. BeautifulSoup

  • detect
  • blog
  • type
  • platform
Read More

a template tag to invoke a method on an object with a variable

The django templating language is quite nice, and specifically limited to guide people in to making their business logic in the view, not in the template itself. Sometimes it can be difficult to do certain things in the template even though it seems like the most appropriate place to do this. I have an application that is heavily influenced by the user that is logged in in several ways. For example let us say I have a list of forums. Each forum has several discussions full of posts. This system of forums and discussions has permissions such that some users can not see some entities. Now, I can produce in the view the query set of what forums a user is allowed to see, and I want this list to display the latest post in each of those forums, but I have to restrict that to the posts that they can see. Easy enough, I have a method on the Forum object that takes a user object and does the appropriate filter to return the latest post that the user can see. The trick is the template is passed the query set of forums, and then iterates through them using the template language. How can it invoke the method on the forum for the latest post that needs the 'user' variable from the template context? The template language lets me say 'forum.latest_post' but I need to pass in 'user'. 'forum.latest_post(user)' does not work because the template language does not allow it. This tag lets me specify an object, the method on that object to call, and the variable to pass to that method. It is not the prettiest thing but with this add on you can do: `{% method_arg forum latest_post user as post %}`

  • tags
Read More

Custom SQL Function; Outputs Template-Friendly Content

This will return a template-friendly list of dictionaries when using custom SQL. The dictionary can be accessed just as a normal model/queryset. Example of use (in view): qkeys = ['artist','album'] query = """ SELECT "artist","album" FROM "music" """ new_list = csql(request,query,qkeys) (in template) {% for row in new_list %} {{ row.artist }} {{ row.album }} {% endfor %}

  • templates
  • custom-sql
Read More

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

3110 snippets posted so far.