A very basic Basic Auth middleware that uses a username/password defined in your settings.py as `BASICAUTH_USERNAME` and `BASICAUTH_PASSWORD`. Does not use Django auth. Handy for quickly securing an entire site during development, for example.
In settings.py:
BASICAUTH_USERNAME = 'user'
BASICAUTH_PASSWORD = 'pass'
MIDDLEWARE_CLASSES = (
'app.module.BasicAuthMiddleware',
#all other middleware
)
Add this to your apache config:
`<Directory /path/to/media>
WSGIAccessScript /path/to/access.wsgi
</Directory>`
Save the snippet as access.wsgi. Set up the paths, and do some authorization checking.
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/')
The above snippet makes all of the settings.py variables accessible in templates. Add this to the context_processors.py file inside your app directory. After that add the below line to the TEMPLATE_CONTEXT_PROCESSORS in your settings.py.
'*app_name*.context_processors.access_to_settings'
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/*)
I often need to filter my change_list by author but my User table is usually pretty crowded and adding the User FK to list_filter would end up with hundreds of user links in the sidebar. This snippets replace those hundreds of links by a simple HTML <input>.
The tag generates a parameter string in form '?param1=val1¶m2=val2'.
The parameter list is generated by taking all parameters from current
request.GET and optionally overriding them by providing parameters to the tag.
This is a cleaned up version of http://djangosnippets.org/snippets/2105/. It
solves a couple of issues, namely:
* parameters are optional
* parameters can have values from request, e.g. request.GET.foo
* native parsing methods are used for better compatibility and readability
* shorter tag name
Usage: place this code in your appdir/templatetags/add_get_parameter.py
In template:
{% load add_get_parameter %}
<a href="{% add_get param1='const' param2=variable_in_context %}">
Link with modified params
</a>
It's required that you have 'django.core.context_processors.request' in
TEMPLATE_CONTEXT_PROCESSORS
These generic views extend default views so that they also do permission checking on per-object basis.
* detail, update and delete - check access for user
* create - create permissions for user on object
* list - narrow object list with permissions
Classes prefixed with Owned are example implementation where user has access to object if designed object attribute references him.
Example:
`create_article = OwnedCreateView.as_view(owner='creator', model=Article, form_class=ArticleForm, success_url='/articles/article/%(id)d')`
Syntax:
{% math <argument, ..> "expression" as var_name %}
Evaluates a math expression in the current context and saves the value into a variable with the given name.
"$<number>" is a placeholder in the math expression. It will be replaced by the value of the argument at index <number> - 1.
Arguments are static values or variables immediately after 'math' tag and before the expression (the third last token).
Example usage,
{% math a b "min($1, $2)" as result %}
{% math a|length b|length 3 "($1 + $2) % $3" as result %}
This one works works with or without query string dicts
defined in the context. And it handles replacement, addition and
removal of values for parameters with multiple values.
Usage:
{% url view %}{% query_string qs tag+tags month=m %}
where `view`, `qs` (dict), `tags` (list of strings) and `m` (number)
are defined in the context. Full detail in the doc string.
Admin-like autodiscover for your apps.
I have copy/pasted this code too many times...Dynamically autodiscover a particular module_name in a django project's INSTALLED_APPS directories,
a-la django admin's autodiscover() method.
This is a very flexible and concise way to [Handle choices the right way](http://www.b-list.org/weblog/2007/nov/02/handle-choices-right-way/) in model fields.
* Preserves order.
* Allows both a human-readable value for display in form `<select>`s as well as a code-friendly short name.
* Mimic's Django's canonical [choices format](http://docs.djangoproject.com/en/1.3/ref/models/fields/#choices).
* Doesn't restrict the value type.
* Memory efficient.
Inspired by [snippet 2373](http://djangosnippets.org/snippets/2373/) to use namedtuples as model field choices.
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.