Snippet List
This is hardcoded to use [django-discover-runner](http://pypi.python.org/pypi/django-discover-runner) since that's my main test runner but could easily be adopted to use Django's own test runner. If you're using a terminal that is capable of showing 256 colors use the `Terminal256Formatter` formatter instead.
Enabled it with the `TEST_RUNNER` setting:
TEST_RUNNER = 'dotted.path.to.highlighted.runner.HighlightedDiscoverRunner'
Where `dotted.path.to.highlighted.runner` is the Python import path of the file you saved the runner in.
- pygments
- testing
- test
- traceback
In case you ever use [requests](http://python-requests.org/) (or [slumber](http://slumber.in/)) to do requests against a Tastypie API that requires API key authentication, this small custom auth class will help you.
Use it like that (with requests):
auth = TastypieApiKeyAuth('jezdez', '25fdd0d9d210acb78b5b845fe8284a3c93630252')
response = requests.get('http://api.foo.bar/v1/spam/', auth=auth)
or with slumber:
auth = TastypieApiKeyAuth('jezdez', '25fdd0d9d210acb78b5b845fe8284a3c93630252')
api = slumber.API("http://api.foo.bar/v1/", auth=auth)
spam = api.spam().get()
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/')
- settings
- decorator
- contextmanager
This middleware will prevent access to the admin if the users IP isn't in the INTERNAL_IPS setting, by comparing the request path with the reversed index URL of the default admin site, ultimately raising a 404 (unless DEBUG = True).
Redirects to the default site (from Django's Sites contrib app), specified by the `SITE_ID` setting.
That's for example useful if you configured your webserver to handle multiple domains with the same virtual host and want to make sure every requests is then redirected to the right domain.
If you feel nostalgic for the old days of crufty URLs, put this middleware somewhere in your Django app and add the first entry in settings.MIDDLEWARE_CLASSES as shown below. Keep in mind that you need to replace 'path.to' with the correct Python path to the middleware.
MIDDLEWARE_CLASSES = (
'path.to.RandomFileExtensionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
)
Note: Although this works it's still a joke.
Use this snippet at the end of your main settings.py file to automagically import the settings defined in each app of `INSTALLED_APPS` that begins with `APPS_BASE_NAME`.
Set `APPS_BASE_NAME` to the base name of your Django project (e.g. the parent directory) and put `settings.py` files in every app directory (next to the `models.py` file) you want to have local settings in.
# works in the Django shell
>>> from django.conf import settings
>>> settings.TEST_SETTING_FROM_APP
"this is great for reusable apps"
Please keep in mind that the imported settings will overwrite the already given and preceding settings, e.g. when you use the same setting name in different applications.
Props to [bartTC](http://www.djangosnippets.org/users/bartTC/) for the idea.
- settings
- import
- reusable
- apps
- applications
This is a customized version of the default `for` template tag which takes an optional `{% else %}` clause that will be displayed if the given array is empty.
from django.template import *
>>> t1 = Template("""
{% load mytags %}
{% for athlete in athlete_list %}
{{ athlete }}
{% else %}
No athlete in list!
{% endfor %}
""")
>>> c1 = Context(
{'athlete_list':
['me', 'myself', 'I']
})
>>> t1.render(c1)
u'me myself I '
>>> c2 = Context({})
>>> t1.render(c2)
u'No athlete in list!'
If you want to automatically override the builtin `for` template-tag add it to the builtins:
from django.template import add_to_builtins
add_to_builtins('python.path.to.mytags')
- template
- tags
- template-tag
- templatetags
- forloop
A Django newforms field which takes another newforms field during
initialization and validates every item in a comma-separated list with
this field class. Please use it like this:
from django.newforms import EmailField
emails = CommaSeparatedValuesField(EmailField)
You would be able to enter a string like "[email protected],[email protected]"
because every email address would be validated when clean() is executed.
This of course also applies to any other Field class.
You can define the sepator (default: ",") during initialization with the
`separator` parameter like this:
from django.newforms import EmailField`
emails = SeparatedValuesField(EmailField, separator="###")
- newforms
- field
- comma
- separated
jezdez has posted 12 snippets.