Simple template tag that allows you to inspect an object in the context for debugging. It will inspect django models and forms using introspection. Dicts and lists are formatted to truncate long data. Pretty much everything else just displays the __str__ representation + class name.
Example output: http://dsanity.net/introspectiontag.html
Usage:
put tag code as file introspection.py in your templatetags directory. Place the html template in your template path under "inspect_object.html".
Then in your template:
{% load introspection %}
{% inspect_object obj "test object" %}
The first parameter is the object to inspect, the second is the name used for display purposes.
I tend to have all my python code together in a 'python' directory.
e.g. a typical project layout of mine looks like:
/python
/python/myproject - project python code
/python/django - local copy of django
/python/foolib - some third party library
/media
/templates
...
Since I don't want to set the python path explicitly I just assume the 'manage.py' is in the right place and use its __file__ variable to set up the python path correctly.
I use the same trick for my settings.py for setting MEDIA_ROOT and TEMPLATE_DIRS.
This hack replaces all INNER JOINs inside to the LEFT OUTER JOINs (see http://code.djangoproject.com/ticket/3592 for explanation).
Use: QLeftOuterJoins(Q(...) | Q(...) & (Q(...) | ....)).
Every now and then you need to have items in your database which have a specific order. As SQL does not save rows in any order, you need to take care about this for yourself. No - actually, you don't need to anymore. You can just use this file - it is designed as kind-of plug-in for the Django ORM.
Usage is (due to use of meta-classes) quite simple. It is recommended to save this snippet into a separate file called `positional.py`. To use it, you only have to import `PositionalSortMixIn` from the `positional` module and inherit from it in your own, custom model (but *before* you inherit from `models.Model`, the order counts).
Usage example: Add this to your `models.py`
from positional import PositionalSortMixIn
class MyModel(PositionalSortMixIn, models.Model):
name = models.CharField(maxlength=200, unique=True)
Now you need to create the database tables: `PositionalSortMixIn` will automatically add a `postition` field to your model. In your views you can use it simply with `MyModel.objects.all().order_by('position')` and you get the objects sorted by their position. Of course you can move the objects down and up, by using `move_up()`, `move_down()` etc.
In case you feel you have seen this code somewhere - right, this snippet is a modified version of [snippet #245](/snippets/245/) which I made earlier. It is basically the same code but uses another approach to display the data in an ordered way. Instead of overriding the `Manager` it adds the `position` field to `Meta.ordering`. Of course, all of this is done automatically, you only need to use `YourItem.objects.all()` to get the items in an ordered way.
Update: Now you can call your custom managers `object` as long as the default manager (the one that is defined first) still returns all objects. This Mix-in absolutely needs to be able to access all elements saved.
In case you find any errors just write a comment, updated versions are published here from time to time as new bugs are found and fixed.
*NOTE Stephen updated his original snippet http://www.djangosnippets.org/snippets/85/ to work with WebFaction, please use his version now*
This code is 95% from Stephen Zabel's snippet at http://www.djangosnippets.org/snippets/85/. However, his snippet, as it was, wouldn't work when enabling SSL for the admin site on Webfaction. For some reason, the default request.is_secure() doesn't behave properly with Webfaction's setup and redirects.
One thing Webfaction does do is add X-Forwarded-ssl='on' to any https requests. So instead of using request.is_secure(), I've just used that.
To setup the admin site with SSL on Webfaction, do the following:
1. Install this middleware wherever you like, and add it to settings.py
2. In your Webfaction panel, create your 'django' application ("application" in the Webfaction sense, not the Django sense)
3. Create two sites. The first, your main site (which I'll call example.com), should use the application 'django' mounted at '/'. Do *not* have HTTPS enabled on this site.
4. For the second site, also use the application 'django', and again mount it to '/', but this time enable HTTPS.
5. In your urls.py, modify the admin URL as follows: `(r'^admin/', include('django.contrib.admin.urls'), {'SSL':True} )`
That should be it! The admin section of the site now requires SSL (as specified in urls.py), and if anyone tries to access the admin via regular http, a redirect to https will occur.
Wizard class - subclass this, supply a done() method and then you can use `MyWizard( [list, of, newforms, classes])` as a view function.
see [#3218](http://code.djangoproject.com/ticket/3218)
Taken from the [longer description on my blog][1]:
> One of the great things about Django is its simple and flexible URL handling. If your Django work, like mine, includes converting existing sites, you’ll probably be doing some URL cleanup along the way...
Just plug your old/new URL pairs into `redirects`.
[1]: http://e-scribe.com/news/290
I once needed to convert a Django project from PostgreSQL to SQLite. At that time I was either unaware of manage.py dumpdata/loaddata or it they didn't yet exist. I asked for advice on the #django IRC channel where ubernostrum came up with this plan:
simple process:
1) Select everything.
2) Pickle it.
3) Save to file.
4) Read file.
5) Unpickle.
6) Save to db.
:)
Or something like that.
First I thought it was funny, but then started to think about it and it made perfect sense. And so dbpickle.py was born.
I've used this script also for migrating schema changes to production databases.
For migration you can write plugins to hook on dbpickle.py's object retrieval and saving. This way you can add/remove/rename fields of objects on the fly when loading a dumped database. It's also possible to populate new fields with default values or even values computed based on the object's other properties.
A good way to use this is to create a database migration plugin for each schema change and use it with dbpickle.py to migrate the project.
See also [original blog posting](http://akaihola.blogspot.com/2006/11/database-conversion-django-style.html) and [my usenet posting](http://groups.google.com/group/django-users/browse_thread/thread/6a4e9781d08ae815/c5c063a288483e07#c5c063a288483e07) wondering about the feasibility of this functionality with manage.py dumpdata/loaddata.
See [trac site](http://trac.ambitone.com/ambidjangolib/browser/trunk/dbpickle/dbpickle.py) for version history.
I know you're thinking, *what the heck could that title mean?*
I often find myself wanting to filter and order by the result of a COUNT(*) of a query using a method similar to the [entry_count example](http://www.djangoproject.com/documentation/db-api/#extra-select-none-where-none-params-none-tables-none). Writing this many times is tedious and hardcoding the table and column names made me cringe, I also wanted the counts to result from more complex queries.
This is a method you can add to your custom Manager to do this easily. It's not an ideal syntax, but it's good for the amount of code required.
Example: suppose we have some articles we want to filter and order by comments and visit logs to show the most popular...
class ArticleManager(models.Manager):
count_related = _count_related
class Article(models.Model):
pub_date = models.DateTimeField(auto_now_add=True)
objects = ArticleManager()
class Comment(models.Model):
article = models.ForeignKey(Article)
is_spam = models.BooleanField(default=False)
class Visit(models.Model):
article = models.ForeignKey(Article)
referrer = models.URLField(verify_exists=False)
search_query = models.CharField(maxlength=200)
Notice how the ArticleManager is given the `count_related` method. Now you can find the most popular like so...
Order by non-spam comments:
Article.objects.count_related(Comment.objects.filter(
is_spam=False)).order_by('-comment__count')
Order by incoming non-search-engine links:
Article.objects.count_related(Visit.objects.filter(
referrer__isnull=False, search_query__isnull=True),
'links').order_by('-links')
Order by total visits:
Article.objects.count_related(Visit).order_by('-visit__count')
Note: Doesn't work if `query` contains joins or for many-to-many relationships, but those could be made to work identically if there's demand.
This is a very simple way to display images within the admin list view. It is not efficient in the sense that the images are being downloaded in original format, however for cases where the images are not regularly accessed it may be a straightforward option.
Can also be tied into WYSIWYG editors like TinyMCE by adding an appropriate href link in the return value.
This middleware will add a log of the SQL queries executed at the bottom of every page. It also includes a query count and total and per-query execution times.
This snippet introduces two tags: `{%dbinfo%}` and `{%dbquerylist%}`. The `{%dbinfo%}` tag returns a string with the # of database queries and aggregate DB time. The `{%dbquerylist%}` tag expands to a set of <LI> elements containing the actual SQL queries executed. If `settings.TEMPLATE_DEBUG` is False, both tags return empty strings.
A middleware we are using to stop "spam" on Curse. It makes the user fill in a captcha box whenever they submit a form unless a cookie is set (which expires by default after 6 hours)
See also [the template](http://www.djangosnippets.org/snippets/128/)
Note: render_template is simply a shortcut function we have for doing render_to_response with a request context
I use this script to export a group of models that I want to import later as initial data. It exports them as serialized json, which is perfect for importing later with the loaddata function in manage.py.
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.