Login

Top-rated snippets

Snippet List

Basic Auth Middleware

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 )

  • middleware
  • basic
  • authentication
  • http-authorization
Read More

Decorator and context manager to override settings

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
Read More

FirstRun Middleware

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/*)

  • middleware
  • django
  • redirect
Read More

Add GET parameters from current request

The tag generates a parameter string in form '?param1=val1&param2=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

  • get
  • request
  • parameters
  • add
Read More

Generic views with row-level permission handling

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')`

  • generic-views
  • permissions
Read More

math tag

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 %}

  • math
  • min
  • max
Read More

Yet another query string template tag

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.

  • url
  • template-tag
  • query-string
Read More

Generic Autodiscovery

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.

  • autodiscover
Read More

Model field choices as a namedtuple

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.

  • choice
  • choices
  • field
Read More

3110 snippets posted so far.