Here is a Django view that turns code like this:
@variables { $varcolor: #333; }
body { color: $varcolor; padding: 20px; }
.space { padding: 10px; }
.small { font-size: 10px; }
#banana(.space, .small) { margin-bottom: 10px; }
And turns it into something like this:
body { color: #333; padding: 20px; }
#banana { padding: 10px; font-size: 10px; margin-bottom: 10px; }
.small { font-size: 10px; }
.space { padding: 10px; }
Notice the variables declaration at the top. The other feature is *extending* - here #banana extends .space and .small.
The url.py entry might look something like this:
(r'^css/(?P<css>(\w|-)+)\.css$','csspp.csspp'),
Here referencing csspp.py in your path (root directory of your site probably). The code also looks for a CSS_DIR setting in your settings file. You will probably want to point straight to your media/css/ directory.
**Known problems**
* There is now way of extending selectors that are already extending something else. In the example code there is now way to extend #banana since it is already extending .small and .space.
Middleware for communicating with Flash Player via Flashticle and Django.
Setup a view at /gateway/math/multiply like so:
def multiply(request, m1, m2):
return m1 * m2
Then in your Flex/Flash app you call "math.multiply" on a NetConnection pointing to http://domain.com/gateway/
Does not yet support authentication.
Make sure we don't create an infinite loop with a self-referencing foreign key.
Many times I have needed category models that reference themselves, providing a flexible way to make children categories, grandchildren categories, etc. If you chain the slugs (or even ids) there's a chance you could end up with an infinite loop.
Assumes a required, unique slug field ('slug') and an optional self-referencing foreign key
('parent'). All_data doesn't give you the object's ID, so we will find it via the unique slug.
If either is not present we pass -- if there's no parent chosen it's not a problem, and if there
is no slug present the submission will fail on that validation instead. It is worth noting that
if the user changes the slug field on submission AND picks a bad parent it will not be caught.
Infinite loop cases:
1. A references A
2. A tries to reference B, which is currently referencing A
If you ever have a need to display something like:
"last update 5 days ago"
"user logged in 2 mins ago"
you can use this script to determine how long ago a timestamp is versus now().
A CompressedTextField to transparently save data gzipped in the database and uncompress at retrieval. Full description at my blog: [arnebrodowski.de/...Field-for-Django.html](http://www.arnebrodowski.de/blog/435-Implementing-a-CompressedTextField-for-Django.html)
! Note - no longer needed
Save this script in the same directory as manage.py and run it through the command line.
It picks up project Command class instances. Something that will hopefully be fixed in the Django SVN version soon.
Heres an example of a command:
#utils/management/commands/sqlallall.py
from django.core.management import call_command
from django.core.management.base import BaseCommand
from django.db import models
class Command(BaseCommand):
help = "Returns sqlall for all installed apps."
def handle(self, *args, **options):
"""
Returns sqlall for all installed apps.
"""
for app in models.get_apps():
call_command("sqlall", app.__name__.split(".")[-2])
This allows for urls in the form of `/grandparent-slug/parent-slug/self-slug/` where the number of parent slugs could be 0 to many.
You'll need to make sure that it is your last urlpattern because it is basically a catch-all that would supersede any other urlpatterns.
Assumes your page model has these two fields:
* `slug = models.SlugField(prepopulate_from=("title",), unique=True)`
* `parent = models.ForeignKey("self", blank=True, null=True)`
A revised version of [zeeg's Sphinx Search ORM](http://www.djangosnippets.org/snippets/231/), using my Sphinx client and adding support for Sphinx's excerpt generator. It's still missing support for search modes/order_by/filter/exclude, but it should be easy and I will add the relevant methods soon as I need them.
Usage is the same as zeeg's class, except that you can pass a field name (or tuple for related objects) to its constructor, that will be used for excerpts:
class MyModel(models.Model):
search = SphinxSearch(excerpts_field='description')
MyModel.search.query('query')
MyModel.search.query('query').count()
Returns an ordered list of the objects in your database.
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 %}
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 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.
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.