This is a very small, simple piece of code, but essential for using fields of type 'money' on MS SQL Server, through FreeTDS. This took me quite some time to hunt down, as get_placeholder() is in fact an undocumented feature.
**Example:**
class MyModel(models.Model):
price = MoneyField()
I think this method is handy, since you don't need to remember if you
need urlquote or urlencode. It does both and adds a question mark
between the path and the get parameters, if later are present.
And it works around a bug in Django: MultiValueDicts (request.GET, request.POST) are handled correctly.
Related: [http://code.djangoproject.com/ticket/9089](http://code.djangoproject.com/ticket/9089)
This is based on a snippet contributed by zbyte64 ( RequireLoginMiddleware) but turned on its head. RequireLoginMiddleware enforces authentication for a subset of urls defined in settings.py. This middleware requires authentication for all urls except those defined in settings.py. The aim is to globally enforce site wide authentication without having to decorate individual views.
To use, add the class to MIDDLEWARE_CLASSES and then define the urls you don't need authentication for. These go in a tuple called PUBLIC_URLS in settings.py. For example:-
PUBLIC_URLS = (
r'project/application/login/',
r'project/application/signup/',
)
By default, authentication is not required for any urls served statically by Django. If you want to subject these to the same validation, add an entry to settings.py called SERVE_STATIC_TO_PUBLIC with a value of True.
Django's templates don't provide much in the way of arithmetic: there is an "add" filter and that is about it. Even if sub, mult and div filters are implemented, it is difficult to chain filters while preserving some complicated expression, such as ((x+3)4-(2-y)/12.75). However, this expression can be converted into Reverse Polish Notation: x 3 + 4 * 2 y - 12.75 / - which is just a sequence of operations (push-value or apply-operator) and can be chained.
To use these filters, first create a new stack for the expression with name|stnew (pass it some locally unique value). To push a number (or template variable) onto the stack, call name|stpush:number (note that you have to tell stpush the name of the stack to push onto). To pop, call name|stpop. To perform an operation, call name|st[add,sub,mult,div,mod]:number. All numbers are integers if they look like integers, or floats otherwise (integers are turned into floats upon division if they need to be). All of these functions return the name of the stack so that they can be chained. When the calculation is finished (i.e. the answer is at the bottom of the stack) call name|stget to retrieve it.
Example (this was used to calculate an inline CSS value:
`left: {{ forloop.counter|stnew|stpush:res.stwkday|stpush:"9.35"|stmult|stpush:res.get_item_left|stpush:"2.75"|stadd|stadd|stget }}em;`
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')
Request-phase cache middleware that checks to make sure the Cache server is running. Starting it if it is not. This is run for every request, it checks to see if it can get a defined item out of the cache, if that fails it tries to set it. Failing that it decides the server is probably crashed, so goes though and attempts to connect to the server. Failing a connection it will launch a new server.
This is probably not useful on large scale multi server deployments as they likely have their own testing for when services crash, but I am using it in a shared hosting environment where I have to run my own copy of memcache manually and cannot setup proper services testing, so I use this to just make sure the cache server is still running.
A subclass of `HttpResponse` which will transform a `QuerySet`, or sequence of sequences, into either an Excel spreadsheet or CSV file formatted for Excel, depending on the amount of data. All of this is done in-memory and on-the-fly, with no disk writes, thanks to the StringIO library.
**Requires:** [xlwt](http://pypi.python.org/pypi/xlwt/)
**Example:**
def excelview(request):
objs = SomeModel.objects.all()
return ExcelResponse(objs)
This is a basic view for a FastCGI authorizer against the Django auth. The idea is to return either a blank response with REMOTE_USER set on success, a forbidden response for failure, or a redirect to a login page when no user is logged in.
I use this view for a Trac instance running on the same (lighttpd) server as Django. lighttpd is set up to use Django as a FastCGI authorizer (using snippet 1149) for the Trac URLs instead of using basic/digest HTTP authentication, so Trac has the same users as Django.
I use this as the FastCGI script for authorizers with lighttpd (though I guess it should work with little change on any other webserver supporting FastCGI). I point it to the same Django project/settings as the normal responder script.
As I use it to gate access to pages not served by Django, I can include those non-Django URLs in the main urls.py, connected to special authorizer view functions (in another snippet).
The two key parts of the script, compared to the equivalent one for Django in the normal FastCGI Responder role, are:
1. Pass the FCGI_AUTHORIZER as the role to WSGIServer
2. Generate a PATH_INFO variable from the REQUEST_URI (FastCGI authorizers aren't given PATH_INFO, but Django needs that to match against the URLconf.)
=== version 2 ===
> Parts of this code are based off of source from *davidcramer* on #django and I'd like to thank him for his assistance.
Example:
# forms.py
...
class ForumPostForm(FieldAccessForm):
class Meta:
model = ForumPost
class FieldAccess:
moderator = FieldAccessLevel(
lambda user, instance: user.get_profile().is_moderator,
enable = ('approve', 'delete', 'edit')
member = FieldAccessLevel(
lambda user, instance: user.is_active,
enable = ('edit',),
exclude = ('approve', 'delete')
...
# template
...
<form action="" method="POST">
<table>
{% for field in form %}
<tr><th>{{ field.label_tag }}</th><td>
{% if not field.field.disabled %}
{{ field }}
{% else %}
{{ field.field.value }}
{% endif %}
</td></tr>
{% endfor %}
</table>
<p><input type="submit" value="Update" /></p>
</form>
...
This class will grant or deny access to individual fields according to simple rules. The first argument must be a user object, but otherwise, this class is instantiated the same as a ModelForm.
To utilize this code, inherit your form from FieldAccessForm, and create an inner class on your form called FieldAccess. Variables added to this inner class must have the same structure as that provided by the FieldAccessLevel class, which defines an access level, and the fields which apply to that access level.
FieldAccessLevel takes as it's first argument a callable rule that validates this access level. That rule will be called with two arguments: 'user' (current user requesting access) and 'instance' (model instance in question).
The keyword arguments to FieldAccessLevel are field groups which are used to determine which fields on this form are to be enabled and/or excluded, when the current user matches this access level. The term exclude indicates fields which are not to be rendered in the form at all.
Any fields not grouped in either 'enable' or 'exclude' will be disabled by default.
Superusers are always assumed to have full access. Otherwise, if a field is not specified with the FieldAccess inner class, then it is disabled by default. In other words, all users (except superusers) are denied access to all fields, unless they are
specifically given access on a per-field basis.
It is worth mentioning that multiple access levels can apply simultaneously, giving a user access to fields from all levels for which he matches the rule.
If a user is denied access to a field, then the widget for that field is flagged as disabled and readonly. The field is also given two new attributes: a boolean 'disabled', and a 'value' containing the instanced model field. These two attributes allow a template author to have great control over the display of the form. For
example, she may render the plain text value of a field instead of the disabled widget.
The FieldAccess inner class also allows one to conditionally exclude fields from being rendered by the form. These exclusions operate very similarly to the standard Meta exclude option, except that they apply only to the access level in question.
Note: The FieldAccess inner class may be used on both the form and the model; however, generally it makes more sense on the form. If you do use FieldAccess on both the form and model, be aware that both definitions will apply simultaneously. All access levels for which the user passes the rule will be processed, regardless of whether they were found on the form or the model.
This GeoDjango subclass substitutes in the Google Maps base layer instead of the default one provided by Open Street Map. Requires the [google.html](http://www.djangosnippets.org/snippets/1145/) and [google.js](http://www.djangosnippets.org/snippets/1146/) templates (must be placed in `gis/admin` somewhere in your template path).
Requires a Google Maps API key -- please abide by Google's [terms of service](http://code.google.com/apis/maps/terms.html).
This exception is util when you want to raise an exception but want its message be shown as a message to the user, with no error 500 or 404 pages.
To use it, just append the middleware in the MIDDLEWARE_CLASSES setting and raises HttpMessage when necessary.