Based on [#2712](../2712/)
"This snippet creates a simple generic export to csv action that you can specify the fields you want exported and the labels used in the header row for each field. It expands on #2020 by using list comprehensions instead of sets so that you also control the order of the fields as well."
The additions here allow you to span foreign keys in the list of field names, and you can also reference callables.
This snippet allows you to use the CommaSeparatedIntegerField to store a set of integers that correspond to a set of choices. There are a couple other snippets that proclaim to do this, but they either don't work with the django 1.4, or are more complex.
When saving an edit to an object from a filtered list view you are, by default, returned to list view without any of your filters applied.
This solves that problem, keeping the filtered view in a session variable until you reach a point where the session key is deleted.
This solution doesn't require changes to template code...this is completely self contained within your own admin.py files.
The solution presented here is a revision of a previous patch, which has been modified for Django 1.4. The Django 1.3 version exists at:
http://djangosnippets.org/snippets/2531/
From chronosllc:
The advantage to our solution over the above linked solution is that under different use cases the user may or may not be redirected to the filtered list_view. For example, if you edit an object and click the save and continue button, then you would lose the filter when you finally finished editing the object and clicked save.
Added on here is a delete of the session key when users add objects, the reasoning we're going this route is we don't want to return users to filtered views when they just added a new object. Your mileage may vary and if so, it's easy enough to fit your own needs.
Showing a list of logged users using the *user_logged_in* and *user_logged_out* signals.
See [login and logout signals](https://docs.djangoproject.com/en/1.4/topics/auth/#login-and-logout-signals) in Django docs.
You need jQuery and Bootstrap 2 and bootstrap-dropdown.js. Apart from that, this should be a perfect drop-in replacement for the normal select widget. A jQuery event callback maintains a hidden input field from the user's selection. Upon loading the page, the hidden input field is set.
The SelectWidgetBootstrap also contains a <noscript> tag containing the normal forms.Select widget.
Example usage:
class MyForm(forms.Form):
group = forms.ModelChoiceField(models.Group.objects.all(), widget=SelectWidgetBootstrap(),
empty_label=_(u'(no group selected)'))
This is a function to take a Q object and construct a function which returns a boolean. This lets you use the exact same filter syntax that Django's managers use and apply it inside list comprehensions, or to non-persistent objects, or to objects of different types with the same attribute names.
This code runs well on Django 1.4 also with the Admin panel.
It's important to get the storage and the path before delete the model or the latter will persist void also if deleted.
Django does not have a clean, built-in mechanism to separate GET and POST implementations. This simple decorator provides this behavior. Django does provide an alternate way using class-based views, but defining class for each of your view functions may be an overkill. You can name the get and post functions anything you wish, but you need to make sure they are returned in the same order (get first and then post).
Example usage:
@formview
def edit(request, id):
form = EditForm(id, request.POST or None)
def get():
return render(request, 'edit.html', {'form' : form})
def post():
if form.is_valid():
form.save(id)
return redirect('list')
return get, post
Code for a RelatedMixin I whipped up, useful in instances where you wish to expose details of a single object, including a related group of owned objects, in the same view. Works well with Django's generic DetailView and UpdateView, or any subclass of SingleObjectMixin.
It's a little cleaner than overriding get_context_data differently for every model you want to expose, uses `only('id')` on querysets it doesn't need anything but relational data from, and makes pulling ownership out of distantly related objects much easier.
Supports simple nested hierarchies of models, ie:
* View a company and all people belonging to it Detail(Company < People)
* Edit a company and all computers belonging to its members Update(Company < People < Computers).
Tested with non-generic One-To-Many and reverse object_sets only.
Just provide an OrderedDict called `related_chain` in your DetailRelatedView that describes the progression of querysets to follow, in the format:
model=Foo,
relation_chain=OrderedDict([
('foreign_key_from_foo_to_bar',Bar.objects.all()),
('foreign_key_from_baz_to_bar',Baz.objects.all())
])
It also takes two optional attributes:
context_list_name="baz_list"
which provides an alias for the final related `object_list` (default=`related_list`), and
keep_intermediaries=True
which, if providing a list deeper than one relation, also passes any intermediary related lists into the context, named after the connecting foreign key, like `bar_list` (default=False).
A decorator that restricts the tags and filters available to template loading and parsing within a function.
This is mainly meant to be used when granting users the power of the DTL. You obviously don't want users to be able to do things that could be potentially malicious.
The {% ssi %} tag, for example, could be used to display sensitive data if improperly configured.
{% load %} gives them access to all the unlimited python code you wrote in your templatetags. {% load sudo %}{% sudo rm -rf / %} o_0
Note that the "load" tag (among others) is not listed in the default tag whitelist. If you parse a template (however indirectly) in a function decorated with this, unlisted builtin tags will behave like undefined tags (ie, they will result in a TemplateSyntaxError).
Since {% load %} is not whitelisted, you may want to include some custom tags or filters as "builtins" for convenience. Simply put the module paths to the libraries to include in the `extra` kwarg or the `extra_libraries` list. Generally, this is not recommended, as these libraries need to be carefully and defensively programmed.
**NOTE**: This **does not** do anything about cleaning your rendering context! That's completely up to you! This merely restricts what tags and filters are allowed in the templates.
Examples:
from django.template.loader import get_template
safe_get_template = use_safe_templates(get_template)
tmpl = safe_get_template('myapp/some_template.html')
from django.template import Template
use_safe_templates(Template)('{% load sudo %}')
# TemplateSyntaxError: Invalid block tag 'load'
Intro
-----
I found a question on SO for which Justin Lilly's answer was correct but not as thorough as I'd like, so I ended up working on a simple snippet that shows how to bind signals at runtime, which is nifty when you want to bind signals to an abstract class.
Bonus: simple cache invalidation!
Question
--------
[How do I use Django signals with an abstract model?](http://stackoverflow.com/questions/2692551/how-do-i-use-django-signals-with-an-abstract-model)
I have an abstract model that keeps an on-disk cache. When I delete the model, I need it to delete the cache. I want this to happen for every derived model as well.
If I connect the signal specifying the abstract model, this does not propagate to the derived models:
pre_delete.connect(clear_cache, sender=MyAbstractModel, weak=False)
If I try to connect the signal in an init, where I can get the derived class name, it works, but I'm afraid it will attempt to clear the cache as many times as I've initialized a derived model, not just once.
Where should I connect the signal?
Answer
------
I've created a custom manager that binds a post_save signal to every child of a class, be it abstract or not.
This is a one-off, poorly tested code, so beware! It works so far, though.
In this example, we allow an abstract model to define CachedModelManager as a manager, which then extends basic caching functionality to the model and its children. It allows you to define a list of volatile keys that should be deleted upon every save (hence the post_save signal) and adds a couple of helper functions to generate cache keys, as well as retrieving, setting and deleting keys.
This of course assumes you have a cache backend setup and working properly.
An "if-style" template tag that checks to see if a user belongs to a one or mores groups (by name).
Usage:
`{% ifusergroup Admins %} ... {% endifusergroup %}
or
{% ifusergroup Admins Clients Programmers Managers %} ... {% else %} ... {% endifusergroup %}`
This is a decorator which will gets Django to try the cache before computing the result of a function. It automatically builds the cache key as a hash of the function name and inputs, and allows you to set whatever timeout you want.
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.