While we're on the topic of SSLRedirect (See snippet 240 and 880) here's what I add to the end of my ssl middleware module, so that SSLRedirect wont break my automated testing.
It simply creates a dummy middleware class that removes the SSL argument, but does not do any redirecting. If you were to simply remove the middleware from settings, the extra SSL argument will then get passed on to all the relevant views.
Of course, you'll need to define a TESTING variable in settings, or change this to something else like settings.DEBUG. Having the separate variable for testing allows you to run your server in DEBUG mode without side effects like the change above.
Snippet 240 is great, but it does not handle flatpages since flatpages are not technically a view. This operates on the request level, not the view level so it will handle flat pages.
**Step 1** Add this class to your MIDDLEWARE_CLASSES
**Step 2** Add an entry in settings.py which is a list of regex to match against urls that u want to have ssl:
SSL_URLS = (
r'/login/',
r'/home/',
r'/super-sensitive-information/',
)
A `models.Manager` subclass that helps to remove some of the boilerplate involved in creating managers from certain queries. Usually, a manager would be created by doing this:
class MyManager(models.Manager):
def get_query_set(self):
return super(MyManager, self).get_query_set().filter(query=blah)
Other managers may return other query sets, but this is especially useful as one may define queries on a table which would be used a lot. Since the only part that ever changes is the `query=blah` set of keyword arguments, I decided to abstract that into a class which, besides taking the repetition out of manager definition, allows them to be and'd and or'd in a manner similar to the `Q` objects used for complex database queries.
`CustomQueryManager` instances may be defined in one of two ways. The first, more laborious but reusable manner, is to subclass it, like so:
class MyManager(CustomQueryManager):
query = Q(some=query)
Then, `MyManager` is instantiated with no arguments on a model, like normal managers. This allows a query to be reused without extra typing and copying, and keeps code DRY.
Another way to do this is to pass a `Q` object to the `__init__` method of the `CustomQueryManager` class itself, on the model. This would be done like so:
class MyModel(models.Model):
field1 = models.CharField(maxlength=100)
field2 = models.PositiveIntegerField()
my_mgr = CustomQueryManager(Q(field1='Hello, World'))
This should mainly be used when a query is only used once, on a particular model. Either way, the definition of `__and__` and `__or__` methods on the `CustomQueryManager` class allow the use of the `&` and `|` operators on instances of the manager and on queries. For example:
class Booking(models.Model):
start_date = models.DateField()
end_date = models.DateField()
public = models.BooleanField()
confirmed = models.BooleanField()
public_bookings = CustomQueryManager(Q(public=True))
private_bookings = public_bookings.not_()
confirmed_bookings = CustomQueryManager(Q(confirmed=True))
public_confirmed = public_bookings & confirmed_bookings
public_unconfirmed = public_bookings & confirmed_bookings.not_()
public_or_confirmed = public_bookings | confirmed_bookings
public_past = public_bookings & Q(end_date__lt=models.LazyDate())
public_present = public_bookings & Q(start_date__lte=models.LazyDate(), end_date__gte=models.LazyDate())
public_future = public_bookings & Q(start_date__gt=models.LazyDate())
As you can see, `CustomQueryManager` instances can be manipulated much like `Q` objects, including combination, via `&` (and) and `|` (or), with other managers (currently only other `CustomQueryManager` instances) and even `Q` objects. This makes it easy to define a set of prepared queries on the set of data represented by a model, and removes a lot of the boilerplate of usual manager definition.
This tag allow you to use C-like switch tag in your templates.
It is useful for sequencial and repetitive `{% ifequal %}` tags.
To install it in your project, you just need to follow [these instructions](http://www.djangoproject.com/documentation/templates_python/#extending-the-template-system)
I often write short test or development scripts that are intended as one-offs. I typically want to execute these scripts from the command line but am always forgetting the necessary steps to set up the Django environment [as described here][bennett].
This snippet allows you execute arbitrary Python scripts from the command line with the context of a given project:
python manage.py execfile /path/to/some/script.py
Add the code to a file named `execfile.py` within the `management/commands` directory of one of your apps ([see here][ref] for details).
[ref]: http://www.djangoproject.com/documentation/django-admin/#customized-actions "Customized Actions"
[bennett]: http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/ "Standalone Django Scripts"
Add-on for auth app of newforms-admin branch, adding more information about users and their groups at user and group list in admin interface. Also, nice example on customization of contributed django admin apps.
It adds the following to the user list interface: fields for is_superuser and is_staff, last login time; by default, short names of groups user is in (mousehover to see full names)
It adds the following to the to group list interface: list of users in your groups.
To enable, just put it somewhere and import it from your main urls.py:
import useradmin
In an admin custom view I had the requirement to modify the upload handlers.
However, the @staff_member_required locked the Files upload handlers as it uses the request.POST - see [Ticket 7654](http://code.djangoproject.com/ticket/7654).
These decorators can be used before other decorators to allow setting of the upload handlers.
Usage example:
@upload_handlers_insert(0, QuotaUploadHandler)
@staff_member_required
def upload(request):
pass
This decorator allows edit or delete for the owner of the record. Snippet applies for every model that has ForeignKey to User. Works for User model too. Works with other decorators as permission_required or similar.
Decorator raise http 403 view if user is not owner.
**Usage**
@permission_required('blogs.change_entry')
@owner_required(Entry)
def manage_entry(request, object_id=None, object=None):
Decorator populates object kwargs if object_id present, otherwise just returns original view function.
@permission_required('blogs.delete_entry')
@owner_required()
def entry_delete(*args, **kwargs):
kwargs["post_delete_redirect"] = reverse('manage_blogs')
return delete_object(*args, **kwargs)
In generic delete wrapper view returns original view function.
Here's a nice way of easily passing only certain settings variables to the template. Because of the way Django looks up context processors, we need a little hack with sys.modules. The [blog entry is here](http://sciyoshi.com/blog/2008/jul/10/dynamic-django-settings-context-processor/).
There has been some discussion about removing `auto_now` and `auto_now_add` some time ago. `auto_now_add` can be replaced be using a callable default value, `auto_now` can't. So I wrote this litte function for my current project (older ones still use `auto_add`) to fill the gap...but I'm not sure if `auto_now` will be removed at all.
These three classes allows you to use enumerations (choices) in more natural model-like style. You haven't to use any magic numbers to set/get field value. And if you would like to make your enumeration a full-fledged django-model, migration should be easy.
Note, that you can subclass Item to add some context-specific attributes to it, such as `get_absolute_url()` method for instance.
Examples are provided in the form of `doctest` in the second half of the snippet.