Use this decorator on a function that returns a dict to get a JSON view, with error handling.
Features:
* response always includes a 'result' attribute ('ok' by default)
* catches all errors and mails the admins
* always returns JSON even on errors
This is a multi file upload widget. That does not require adding multiple file input fields. It requires jQuery.MultiUpload (http://www.fyneworks.com/jquery/multiple-file-upload/)
This code provides a Django model for photos based on Flickr, as well as a script to perform a one-way sync between Flickr and a Django installation.
*Please note that the snipped contains code for two files, update.py and a Django model.*
*The two chunks are separated by:*
"""
END OF FLICKRUPDATE
"""
"""
START DJANGO PHOTO MODEL
Requires django-tagging (http://code.google.com/p/django-tagging/)
"""
My model implements tagging in the form of the wonderful django-tagging app by Jonathan Buchanan, so be sure to install it before trying to use my model.
The flickrupdate.py code uses a modified version of flickerlib.py (http://code.google.com/p/flickrlib/). Flickr returns invalid XML occasionally, which Python won't stand for. I got around this by wrapping the return XML in `<flickr_root>` tags.
To modify flickrlib to work with my code, simply change the this line:
return self.parseData(getattr(self._serverProxy, '.'.join(n))(kwargs))
to:
return self.parseData('<flickr_root>' + getattr(self._serverProxy, '.'.join(n))(kwargs) + '</flickr_root>')
I hate this workaround, but I can't control what Flickr returns.
flickrupdate will hadle the addition and deletion of photos, sets and tags. It will also keep track of photos' pools, although, right now, it doesn't delete unused pools. This is mostly because I don't care about unused pools hanging around. It's a simple enough addition, so I'll probably add it when I have a need.
Be sure to set the appropriate information on these lines:
api_key = "YOUR API KEY"
api_secret = "YOUR FLICKR SECRET"
flickr_uid = 'YOUR FLICKR USER ID'
I hadn't seen a Django model and syncing script, so I threw these together. I hope they will be useful to those wanting start syncing their photos.
It allows you to create pdf much like normal html code taking advantage of django's template engine. It requires the trml2pdf module from [OpenReport](http://sourceforge.net/projects/openreport) and can be used like `render_to_response()`. *prompt* specifies if a "save as" dialog should be shown to the user while *filename* is the name that the browser will suggest in the save dialog.
This module defines a template tag `{% ifactive %}` that lets you determine which page is currently active. A common use case is for highlighting the current page in a navigation menu.
It uses the same syntax for specifying views as the `{% url %}` tag, and determines whether a particular page is active by checking if the same view is called with the same arguments, instead of just comparing URLs. As a result, it can handle cases where different URLs map to the same view.
Example usage:
<a {% ifactive request page1 %}class='active'{% endifactive %}
href='{% url page1 %}'>Page 1</a>
<a {% ifactive request page2 %}class='active'{% endifactive %}
href='{% url page2 %}'>Page 2</a>
...
<a {% ifactive request pageN %}class='active'{% endifactive %}
href='{% url pageN %}'>Page N</a>
It also can be extended to further reduce the amount of repetitive code. For instance, you could write a template tag that has class='active' as the block contents, and always gets the variable from context['request']:
def do_activeif(parser, token):
"e.g. <a {% activeif page1 %} href='{% url page1 %}'>Page 1</a>"
tag_args = token.contents.split(' ')
view_name = tag_args[1]
args, kwargs = _parse_url_args(parser, tag_args[2:])
return ActiveNode('request', view_name, args, kwargs, NodeList(TextNode('class="active"')))
register.tag('activeif', do_activeif)
Note that you will have to add the ActiveViewMiddleware to your settings.py:
MIDDLEWARE_CLASSES = (
...,
'path.to.this.module.ActiveViewMiddleware'
)
You may also want to add this template tag as a built-in, so you don't have
to call `{% load %}`. In somewhere that's imported by default (e.g. where you
define your views), add:
from django import template
template.add_to_builtins('path.to.this.module')
Use these tags and filter when you're rolling your own search results. This is intended to be a whole templatetags module. I keep it in my apps as `templatetags/search.py`. These should not be used to perform search queries, but rather render the results.
### Basics
There are three functions, each has both a tag *and* a filter of the same name. These functions accept, at a minimum, a body of text and a list of search terms:
* **searchexcerpt**: Truncate the text so that each search term is shown, surrounded by some number of words of context.
* **highlight**: Wrap all found search terms in an HTML span that can be styled to highlight the terms.
* **hits**: Count the occurrences of the search terms in the text.
The filters provide the most basic functionality as described above, while the tags offer more options as arguments, such as case sensitivity, whole word search, and saving the results to a context variable.
### Settings
Defaults for both the tags and filters can be changed with the following settings. Note that these settings are merely a convenience for the tags, which accept these as arguments, but are necessary for changing behavior of the filters.
* `SEARCH_CONTEXT_WORDS`: Number of words to show on the left and right of each search term. Default: 10
* `SEARCH_IGNORE_CASE`: False for case sensitive, True otherwise. Default: True
* `SEARCH_WORD_BOUNDARY`: Find whole words and not strings in the middle of words. Default: False
* `SEARCH_HIGHLIGHT_CLASS`: The class to give the HTML span element when wrapping highlighted search terms. Default: "highlight"
### Examples
Suppose you have a list `flatpages` resulting from a search query, and the search terms (split into a list) are in the context variable `terms`. This will show 5 words of context around each term and highlight matches in the title:
{% for page in flatpages %}
<h3>{{ page.title|highlight:terms }}</h3>
<p>
{% searchexcerpt terms 5 %}
{{ page.content|striptags }}
{% endsearchexcerpt %}
</p>
{% endfor %}
Add highlighting to the excerpt, and use a custom span class (the two flags are for case insensitivity and respecting word boundaries):
{% highlight 1 1 "match" %}
{% searchexcerpt terms 5 1 1 %}
{{ page.content|striptags }}
{% endsearchexcerpt %}
{% endhighlight %}
Show the number of hits in the body:
<h3>{{ page.title }}
(Hits: {{ page.content|striptags|hits:terms }})
</h3>
All tags support an `as name` suffix, in which case an object will be stored in the template context with the given name; output will be suppressed. This is more efficient when you want both the excerpt and the number of hits. The stored object depends on the tag:
* **searchexcerpt**: A dictionary with keys "original" (the text searched), "excerpt" (the summarized text with search terms), and "hits" (the number of hits in the text).
* **searchcontext**: A dictionary with keys "original", "highlighted", and "hits", with obvious values.
* **hits**: Just the number of hits, nothing special.
Getting both the hits and the excerpt with "as":
{% searchexcerpt terms 3 as content %}
{{ page.content|striptags }}
{% endsearchexcerpt %}
<p>Hits: {{ content.hits }}<br>{{ content.excerpt }}</p>
### More
For more examples see [Brian Beck's Text Adventure][announcement].
[announcement]: http://blog.brianbeck.com/post/29707610
This is an extract of an example for use of "pisa" <http://www.htmltopdf.org> in "django". It shows the easiest way possible to create PDF documents just using HTML and CSS. In "index" we see the definition of the output of a form in which HTML code can be typed in and then on the fly a PDF will be created. In "ezpdf_sample" we see the use of templates and contexts. So adding PDF to your existing Django project could be just a matter of some lines of code.
The class LocationField renders a form field with map (from google maps) and a mark. It allows the user to drag the mark to point at some particular location, whose value (lat, lng) is saved in a hidden field.
It requires jquery and google maps.
This is an extendend version of the Rails Flash implementation by Sean Patrick Hogan that supports different message types.
**Setting a flash message:**
request.flash.error = 'Item could not be saved'
request.flash['error'] = 'Item could not be saved'
request.flash['foo'] = 'bar'
**Displaying a flash in the view:**
<!-- show the error message -->
{% if flash.error %}An error occured:{{ flash.error }}{% endif %}
<!-- just show the first message found -->
{% if flash %}An error occured:{{ flash }}{% endif %}
<!-- show all messages -->
{% for msg in flash %}{{ msg.type }}: {{ msg.msg }}{% endfor %}
Note that it still works with simple strings as well. Feel free to just use it like this:
request.flash = "Message"
And:
{% if flash %}{{ flash }}{% endif %}
However, be aware that once you did this, you destroyed the Flash() dict and thus lost the extended functionality.
You can use request.flash.clear() to remove all messages.
A simple decorator that requires a user to be logged in. If they are not logged in the request is examined for a 'authorization' header.
If the header is present it is tested for basic authentication and the user is logged in with the provided credentials.
If the header is not present a http 401 is sent back to the requestor to provide credentials.
The purpose of this is that in several django projects I have needed several specific views that need to support basic authentication, yet the web site as a whole used django's provided authentication.
The uses for this are for urls that are access programmatically such as by rss feed readers, yet the view requires a user to be logged in. Many rss readers support supplying the authentication credentials via http basic auth (and they do NOT support a redirect to a form where they post a username/password.)
Use is simple:
`
@logged_in_or_basicauth
def your_view:
...
`
You can provide the name of the realm to ask for authentication within.
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.
A couple of utility `Node` subclasses that will automatically cache thier contents.
Use `CachedNode` for template tags that output content into the template:
class SomeNode(CachedNode):
def get_cache_key(self, context):
return "some-cache-key"
def get_content(self, context):
return expensive_operation()
Use `CachedContextUpdatingNode` for tags that update the context:
class AnotherNode(CachedContextUpdatingNode):
# Only cache for 60 seconds
cache_timeout = 60
def get_cache_key(self, context);
return "some-other-cache-key"
def get_content(self, context):
return {"key" : expensive_operation()}
This middleware will add a log of the SQL queries executed at the bottom of every page. It also includes a query count and total and per-query execution times.
You're looking at the most-bookmarked snippets on the site; if you'd like to help useful snippets show up here, sign up for an account and you'll get your own bookmarks list.