When you have two models joined by a foreign key, it's common to want to retrieve a set of objects from the "target" of the foreign key based on whether there are any objects "pointing" to them. This snippet demonstrates how to do so, using the `extra` method of the default model manager.
Note that this is probably more efficient than using two ORM methods (e.g., selecting all values from one table, and using an `id__in` lookup on the other) since it does the whole thing in one query and avoids instantiating any intermediate objects.
Validator to verify a password is SAS70 compliant: greater than or equal to eight characters, and contains at least three out of the four characters( Uppercase, Lowercase, Number, Special Character ).
The XhtmlDegraderMiddleware class is designed to make it easier to deploy XHTML contents onto the World Wide Web. The correct MIME media type for sending XHTML is `application/xhtml+xml` -- the `text/html` media type is also acceptable provided [certain guidelines](http://www.w3.org/TR/2002/REC-xhtml1-20020801/#guidelines) are followed.
The vast majority of web browsers released from 2002 onwards have good XHTML support; this includes Mozilla Firefox, Opera, and Apple Safari. Two notable exceptions are Internet Explorer 7.0 and Netscape Navigator 4.8; instead of displaying XHTML, they present the user with a download dialog instead.
The role of the XHTML Degrader, then, is to automatically detect when browsers do not support XHTML, and to degrade the contents into something they're capable of rendering.
**How it works**
XhtmlDegraderMiddleware checks the content type of all HTTP responses. If the XHTML media type is set, the `Accept` request header is examined to determine whether the user agent actually supports XHTML. If so, the contents is sent unaltered. If not, a number of silent changes are made to make the response more friendly to XHTML-challenged browsers and web crawlers.
Firstly, the `Content-Type` header is set to the HTML media type. Any XML processing instructions are removed, and a `DOCTYPE` is added if none is present. In the case of Internet Explorer, this should ensure the content is rendered in "standards compliance" mode. Empty elements are made to have a space before their trailing slash.
N.B. If an HTTP response is already set to `text/html`, or set to any media type other than `application/xhtml+xml`, the middleware will have no effect. Note also that if you use GZipMiddleware, you should ensure that it appears in your MIDDLEWARE_CLASSES setting before XhtmlDegraderMiddleware, to allow the XHTML Degrader to act first.
Simple tag to enable easy parsing of inline code within a template. Usage: {% stylize "language" %}...language text...{% endstylize %}. Make sure to set the language for Pygments to parse as the first argument to the tag. You will also need to include a copy of the CSS that Pygments uses. The [Pygments](http://pygments.org/) library is required for this tag.
I just converted the autop filter from Drupal (which is itself based on a Wordpress filter) from PHP to Python. I had to change the format of the regular expressions a bit and make them raw strings, but otherwise the function is unchanged. It should work exactly like the original function.
A BooleanField indicating privacy is common on models, but the name of the field and whether the field being True indicates private or public both may change across models. If there is more than one potentially private model, a common interface is needed. A commonly-named method would do the job with `[a for a in MyModel.objects.all() if not a.is_private()]`, but it would still retrieve private instances from the database only to filter them out.
This approach puts the name of the privacy field and whether that field being True indicates private or public in a tuple attribute of the model class. A chainable method is added to all QuerySet objects.
example use:
class MyModel(models.Model):
is_public = models.BooleanField(default=True)
# ...
privacy_field = ("is_public", False)
\>\>\> publicMyModels = MyModel.objects.all().exclude_private()
\>\>\> values = publicMyModels.values()
This tag makes it easy to include menu or navigation bars in an application's pages, even in a 'tabbed' fashion. (The actual appearance is styled in CSS; this example uses UL tags that are then supposed to be styled by a "display: inline" attribute to be rendered as horizontal bars.)
One of the things about Django that has always irked me is that there seems to be no standard facility for just loading a page and displaying it, simply. Yes, there is the flatpages module, but it is primarily designed for loading content from a DB. While you specify a custom template and put in junk values for the DB content, it just feels like extra, unnecessary work.
Thinking about the problem some more, I borrowed from the idea of flatpages and implemented a view that will load an otherwise unmapped template off the filesystem and render it. This is very useful when converting an existing site over. Just copy your files over. No need to map anything in the URL conf or use the admin to add any flatpage entries. Since it'll render the template, too, you can even use tags and what not, so it need not be a static page.
I hate when my unittest hits database. Especially when each test case needs different dataset.
So I wrote this db mock, that's local to specific test and uses sqlite3 in-memory db.
Usage (nosetests):
class TestMainNoData(DbMock):
'testing main function with no meaningful data'
def test_no_posts(self):
'there are no posts'
assert models.Post.objects.count() == 0, 'should be no feeds'
This is based on [Snippet 161](/snippets/161/)
It marks duplicated SQL queries.
To avoid duplicates read:
[Caching and Queryset](http://www.djangoproject.com/documentation/db-api/#caching-and-querysets)
Sept. 07: Updated for current trunk: 'response' behaves like 'response.header'
22. October '07: Log into directory.
A simple macro system that makes it possible to reuse previously defined
blocks, optionally with a custom context, similar to the macro
functionality in Jinja.
It requires some workarounds/hacks because we cannot reach
all the data from inside the django template system that we need, but it
seems to work pretty well so far. It is, however, also pretty untested at this point, so use at your own risk.
Examples:
base.html:
<!--
This is mandatory if you want to use the repeat-tag in
a template. It should as placed as earily as possible.
See below for how to mix with template inheritance.
-->
{% enablemacros %}
<!-- Note that {{ param }} does not exist. -->
{% block foo %}
A standard django block that will be written to the output.
{% if param %}{{ param }}{% endif %}
{% endblock %}
{% macro bar %}
Pretty much the same thing as a django block (can even be
overridden via template inheritance), but it's content
will NOT be rendered per default. Please note that it
ends with ENDBLOCK!
{% if param %}{{ param }}{% endif %}
{% endblock %}
<!-- Render foo for the second time -->
{% repeat foo %}
<!-- Render foo bar the first time -->
{% repeat bar %}
<!-- Render both blocks again, and pass a parameter -->
{% repeat foo with "Hello World" as param %}
{% repeat bar with "Hello World" as param %}
{% macro form %}do stuff with: {{ form }}{% endblock %}
{% for form in all_forms %}
{% repeat display %} <!-- will have access to {{ form }}
{% endfor %}
extend.html:
<!--
{% extends %} requires that it be the first thing in a template,
and if it is, everything except for block tags is ignored, so
{% enablemacros %} won't work. Instead, use:
-->
{% extends_with_macros 'base.html' %}
{% block foo %}
Will override "foo" in base.html
{% endblock %}
{% block bar %}
Will override the macro block "bar" in base.html. Whether
this is defined as block or macro doesn't matter.
{% endblock %}
Todo:
* This (both tags used) results in infinite recursion:
{% extends_with_macros "somefile" %}{% enablemacros %}
In your settings file:
TEMPLATE_TAGS = (
"djutils.templatetags.sqldebug",
)
Make sure load_templatetags() gets called somewhere, for example in your apps __init__.py
*Edit: Updated to work with templatetag libraries that use certain critical django-bits.*
I've been using this along with [prototype](http://www.prototypejs.org) to make simple ajax calls. In essence you make the calls from the client with...
new Ajax.Request('url',{parameters:{'someparam':$('someparam').value}}); return false;
On the onsubmit event of a form, onclick or whatever. Note that the return false is important to prevent the page from reloading. Sending some javascript to be executed back to the client is then as simple as setting up your view to return:
return HttpJavascriptResponse('alert("boing");')
So, yeah, prototype does the real work and this class does little other than make it clear what our intentions are and reduce the opportunities for typos. But it works for me.
Building on [jcroft's snippet](http://www.djangosnippets.org/snippets/17/), here's a slightly more advanced version which has two filters, one for basic text and the other for html snippets.
Usage is like so:
<h2>{{ blog_entry.headline|escape|widont }}</h2>
{{ blog_entry.html|widont_html }}
On top of Jeff's reasons for using these filters, they are important because they help keep one of [God's commandments](http://www.ebible.com/bible/NIV/Exodus+22%3A22). ;)
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.