From: [incredible times](http://incredibletimes.org)
With inspiration from: [Unethical Blogger](http://unethicalblogger.com/2008/05/03/parsing-html-with-python.html)
This code parses any provided HTML content, and extracts a number of paragraphs specified, with all the content and tags inside them.
Example:
Template variable "content" contains:
<a href="#>some text</a>
<p><strong>Testing</strong>testing testing this is a tester's life</p>
<div>I wont see the world</div>
<p>Another paragraph</p>
So, place this code in any loaded template module (inside a templatetags folder of your app... i.e. myapp/templatetags/myutils.py)
{% load myutils %}
{{ content|paragraphs:"1"}}
Would return:
<p><strong>Testing</strong>testing testing this is a tester's life</p>
Whereas
{% load myutils %}
{{ content|paragraphs:"2"}}
Returns:
<p><strong>Testing</strong>testing testing this is a tester's life</p>
<p>Another paragraph</p>
HTML allows an option in a <select> to be disabled. In other words it will appear in the list of choices but won't be selectable. This is done by adding a 'disabled' attribute to the <option> tag, for example:
`<option value="" disabled="disabled">Disabled option</option>`
This code subclasses the regular Django Select widget, overriding the render_option method to allow disabling options.
Example of usage:
class FruitForm(forms.Form):
choices = (('apples', 'Apples'),
('oranges', 'Oranges'),
('bananas', {'label': 'Bananas',
'disabled': True}), # Yes, we have no bananas
('grobblefruit', 'Grobblefruit'))
fruit = forms.ChoiceField(choices=choices, widget=SelectWithDisabled())
Ordinarily, it is not possible to edit Group membership from the Group admin because the m2m relationship is defined on User. With a custom form, it is possible to add a ModelMultipleChoiceField for this purpose. The trick is to populate the initial value for the form field and save the form data properly.
One of the gotchas I found was that the admin framework saves ModelForms with commit=False and uses the save_m2m method when the group is finally saved. In order to preserve this functionality, I wrap the save_m2m method when commit=False.
If you did tried to use `reverse` function to set `success_url` in class based generic views and you have got an exception, this helper function may help.
Put this snipped in some file, for example utils.py and import this function.
A simple model ColorField that allows picking from a predefined list (currently picked up from settings.py
The widget displays as a row of coloured SPAN's with the hex code inside. Simply click to choose a color.
(requires jQuery in the page assigned to it's normal $ shortcut. Easy to change this is you don't use jQuery in this way)
Overriding settings
-------------------
For testing purposes it's often useful to change a setting temporarily and revert to the original value after running the testing code. The following code doubles as a context manager and decorator. It's used like this:
from django.test import TestCase
from whatever import override_settings
class LoginTestCase(TestCase):
@override_settings(LOGIN_URL='/other/login/')
def test_login(self):
response = self.client.get('/sekrit/')
self.assertRedirects(response, '/other/login/?next=/sekrit/')
The decorator can also be applied to test case classes:
from django.test import TestCase
from whatever import override_settings
class LoginTestCase(TestCase):
def test_login(self):
response = self.client.get('/sekrit/')
self.assertRedirects(response, '/other/login/?next=/sekrit/')
LoginTestCase = override_settings(LOGIN_URL='/other/login/')(LoginTestCase)
On Python 2.6 and higher you can also use the well known decorator syntax to
decorate the class:
from django.test import TestCase
from whatever import override_settings
@override_settings(LOGIN_URL='/other/login/')
class LoginTestCase(TestCase):
def test_login(self):
response = self.client.get('/sekrit/')
self.assertRedirects(response, '/other/login/?next=/sekrit/')
Alternatively it can be used as a context manager:
from django.test import TestCase
from whatever import override_settings
class LoginTestCase(TestCase):
def test_login(self):
with override_settings(LOGIN_URL='/other/login/'):
response = self.client.get('/sekrit/')
self.assertRedirects(response, '/other/login/?next=/sekrit/')
Simple piece of middleware that redirects all requests to **settings.FIRSTRUN_APP_PATH**, until a lockfile is created.
Tested on 1.3 only, but I do not believe it requires any special functionality beyond that provided in 1.1
This is useful if you need to force a user to run an installer, or do some configuration before your project can function fully.
At first glance, such a thing would generate a lot of hits on the disk. However, once the lockfile has been created, the middleware unloads itself, so when a project is in a production environment, the lockfile is only checked once per process invocation (with passenger or mod_wsgi, that's not very often at all).
Once your user has completed your FirstRun app, simply create the lockfile and the project will function as normal.
For it to function, the following settings must be configured:
* **settings.PROJECT_PATH** - absolute path to project on disk (e.g. */var/www/project/*)
* **settings.FIRSTRUN_LOCKFILE** - relative path of the lockfile (e.g. */.lockfile*)
* **settings.FIRSTRUN_APP_ROOT** - relative URL of the App you want to FirstRun (eg.*/firstrun/*)
Originally based on: [http://djangosnippets.org/snippets/1872/](http://djangosnippets.org/snippets/1872/)
The way the original snippet formatted sql didn't work for mysql properly so I taught it to use the sqlparse python module. Now it looks like this when settings.DEBUG=True:
SQL executed:
SELECT "django_session"."session_key",
"django_session"."session_data",
"django_session"."expire_date"
FROM "django_session"
WHERE ("django_session"."session_key" = d326108d313a2e5c5fb417364b005ab9
AND "django_session"."expire_date" > 2011-04-08 14:54:13.969881)
took 0.001 seconds
SELECT "auth_user"."id",
"auth_user"."username",
"auth_user"."first_name",
"auth_user"."last_name",
"auth_user"."email",
"auth_user"."password",
"auth_user"."is_staff",
"auth_user"."is_active",
"auth_user"."is_superuser",
"auth_user"."last_login",
"auth_user"."date_joined"
FROM "auth_user"
WHERE "auth_user"."id" = 2
took 0.000 seconds
Additionally, this middlware is enabled conditionally based upon the url query string "debug". You can enable it for a single request by appending: ?debug=true to the url.
Based on discussion on [http://thebuild.com/blog/2010/12/14/using-server-side-postgresql-cursors-in-django/](http://thebuild.com/blog/2010/12/14/using-server-side-postgresql-cursors-in-django/) and [http://thebuild.com/blog/2010/12/13/very-large-result-sets-in-django-using-postgresql/](http://thebuild.com/blog/2010/12/13/very-large-result-sets-in-django-using-postgresql/) but instead implements them via extending the psycopg2 backend which allows you to use all of django's machinery without having to resort to using raw cursors.
Usage:
qs = Model.objects.all()
with server_side_cursors(qs, itersize=100):
for item in qs.iterator():
item.value
if random_reason_to_break:
break
Setup:
In your own project create the package hierarchy myproject.db.backends.postgresql_psycopg2 and place the code in base.py.
In your settings.py set the database ENGINE to be 'myproject.db.backends.postgresql_psycopg2'.
If you using south you'll have to let it know its a postgresql_psycopg2 backend by adding to SOUTH_DATABASE_ADAPTERS (see south documentation).
Note:
Make sure your using psycopg >= 2.4 for efficient named (server side) cursor iteration.
This is useful for randomizing an iterable of objects in place in a django template. Usage:
{% load shuffle %}
{# now some_list is ordered #}
{% shuffle some_list %}
{# now some_list is randomized #}
Python includes (and [Django recommends](http://docs.djangoproject.com/en/dev/topics/email/?from=olddocs#testing-e-mail-sending)) a simple email debugging server which prints mail to stdout. The trouble is, unlike any half-competent mail reader, long lines are broken up, and thus long URLs don't work without modification.
This snippet simply unwraps long lines (broken by "=") so long URLs can be easily copied/pasted from the terminal.
Save this snippet into a file named "better.py" and execute it.
Adds to Django 1.2 tag `{% elif %}`
{% if user.nick == "guest" %}
Hello guest!
{% elif user.nick == "admin" or user.is_admin %}
Hello admin!
{% elif user %}
You are registered user
{% else %}
Login to site
{% endif %}
Snipped designed for [gaeframework.com](http://www.gaeframework.com)
Inspired by snippets: [#1572](http://djangosnippets.org/snippets/1572/) and [#2243](http://djangosnippets.org/snippets/2243/)
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.