Prerequisites: [Python Imaging Library](http://www.pythonware.com/products/pil/)
This function scales a given image (provided as binary data in any format the PIL supports) to a specified size.
If the force parameter is True, the function makes sure that the resulting image is exactly the specified size, cropping and scaling it as necessary (but never distorting it) to make sure the whole image area is filled out.
If force is False, it simply uses the thumbnail function provided by the PIL, which preserves the image aspect ratio and does not increase the image dimensions beyond those of the original file, so you may not get an image that has the exact dimensions you specified.
The result image is returned as JPEG data.
Useful for when you want to use an instance's values as the initial values of a form which you didn't use `form_for_instance` to create.
Handles foreign keys and many-to-many fields just fine.
Super stripped down filter to truncate after a certain number of letters. Ex: {{ long_blurb|truncchar:20 }} will display 20 characters of the long blurb followed by "..."
Apparently Internet Explorer (6 and 7) have a bug whereby if you blindly attach a PDF or some other file, it will choke. The problem lies in the Vary header (bug described in http://support.microsoft.com/kb/824847/en-us?spid=8722&sid=global).
To use, just add to the beginning of your middleware classes.
**Problem**:
You search by firing POST and paginate by firing GET, so search results disappear on GET. I want to preserve searching results, so user can paginate them.
First I try to use some static class to keep search results, but this solution has bug (thanks to svetlyak). In multiuser environment other user searching got results from previous one. No @cache_control(private=True) helps so I decided to change searching schema by using GET in the first place and to supply query string on each 'paging' request. Also added some memory cache that expires after 5 min
**In template**
Please append query to each paging link:
<a href="?page={{ page_number }}
&search_query={{ query|urlencode }}">
{{ page_number }}</a>
This snippet should keep search results on pagination in multiuser environment.
Nutshell: Subclass this form with the required fields defined to automatically generate a form based on a model in a similar fashion to how form_for_model works, but in a way that tries to be a little easier if you want to customize the form. It handles updates and creations automatically as long as any database field requirements are met.
This is something I made while trying to understand newforms, and is my own attempt at something between the simplicity of a stock form_for_model form, and a full blown custom form. The proper way is to use a callback function to customize form_for_model, but that felt cumbersome so I did it my way :) It works for me, but I'm relatively new to both python and Django so please test yourself before trusting.
The newforms fields are more capable than the django models fields. In this snippet, we subclass models.IntegerField, and add min_value and max_value.
e.g.
age = MMIntegerField('How old are you?', min_value=13, max_value=120)
Simple anti-spam field which will cause the form to raise a `ValidationError` if the value in this field changes. Displays as a CSS hidden `<input type="text" />` field.
If you specify a `class` in the `attrs` of the widget, the default `style="display:none;"` won't be rendered with the widget so that you can use a predefined CSS style to do your hiding instead. You can also cause the widget to be wrapped in an html comment to ensure it is not visible to the end user:
class EmailForm(Form):
email = EmailField()
website = HoneypotField(widget=HoneypotWidget(
attrs={'class':'fish'}, html_comment=True))
Middleware for stripping all html comments from the response content before returning it to the client.
This will also strip inline javascript with htmlcomments put around it!
Newforms are made to make any kind of customizations easy. Sometimes standard methods of rendering HTML/XML/other content of the django.newforms is not enough to completely satisfy all web design needs so you may want to present forms in own templates.
Using templates to render output as HTML or XML is straighforward, and in many cases easier then using standard approach.
Step by step usage guide:
1. Create file in your project yourproject/utils/newforms.py and place Class TemplatedForm there
2. Create newforms subdirectory in templates dir, and post 2 templates there (form.html, field.html) from the documentation code for TemplatedForm class
3. Inherit from TemplatedForm in your form class to use this form.
This is a minor modification to [Upload a file using newforms](http://www.djangosnippets.org/snippets/95/) as posted by [mboersma](http://www.djangosnippets.org/snippets/95/).
I altered the ZipUploadForm by removing lines 33 - 34:
if 'zip_file' in self.clean_data:
zip_file = self.clean_data['zip_file']
and adding a return statement to clean_zipfile, which returns the validated zip file. I also added the line:
zip_file.clean = clean_zipfile
so that when the full_clean() in called on the form, clean_zipfile will automatically run.
All other code (the view & template) remain the same.
** Disclaimer **
I'm not *that* familiar with newforms, so please forgive me if some the explanation as to why this works is incorrect ;) Who knows, maybe the first guy had it right.
create_object and update_project modified to handle newforms (including FileFields). In addition, I have added some extras:
1. extra_fields - this is a dict or callable that contains additional fields to be passed to the form, for example stuff that is in the session.
2. on_success - callback called if form is valid and object created/updated, if this is not set the default behaviour is to send a redirect
3. on_failure - callback called if form is invalid, the default is to redisplay the form.
Note that once newforms are finally done these functions are likely to be redundant, as generic views will be updated to use the newforms API, so use with caution.
*I suppose I'm kind of stubborn, but I prefer to use underscores to replace spaces and other characters. Of course, that shouldn't hold you back from using the build-in slugify filter :)*
** Forcing the slug to use ASCII equivalents: **
Transforming titles like "Äës" to slugs like "aes" was kind of a trial and error job. It now works for me. I hope `_string_to_slug(s):` proves a rather stable solution. Yet the worst-case scenario is that such characters are lost, I guess that is acceptable.
Other ways of dealing with this problem can be found at [Latin1 to ASCII at Activestate](http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/251871) or in the comments below.
**How to use:**
The slug fields in your model must have prepopulate_from set, the fields specified in it are used to build the slug.
To prevent duplicates, a number is added to the slug if the slug already exists for the current field in another, previous, object. I guess there should be a cleaner way to distinguish between creating a new db entry or updating an existing one, sadly, the db back-end is kind of a black-box to me. At least this works ;)
I choose not to alter the slug on an update to keep urls more bookmarkable. You could even extend this further by only updating the slug field if it hasn't been assigned a value.
You can download these files from [here](http://huangyilib.googlecode.com/svn/trunk/mashi_django)
Django template, mako, genshi, they are the best three templates in python, aren't they?
How to use these files ?
[Using Mako in Django](http://fuzzythinker.blogspot.com/2007/04/using-mako-in-django.html)
-- by John Leung
You're looking at the top-rated snippets currently on the site; if you'd like to contribute, sign up for an account and you'll be able to rate any snippet you see.