You can use this template loader if you want to use template specifically from one app. Useful mainly in overriding admin templates - just make your own `admin/change_form.html` and have it extend `admin:admin/change_form.html` withou creating any symlinking or copying django admin's templates to alternate location.
Part of the [ella project](http://www.ellaproject.cz/).
This allows you to create an alphabetical filter for a list of objects; e.g. `Browse by title: A-G H-N O-Z`. See [this entry](http://developer.yahoo.com/ypatterns/pattern.php?pattern=alphafilterlinks) in Yahoo's design pattern library for more info.
NamePaginator works like Django's Paginator. You pass in a list of objects and how many you want per letter range ("page"). Then, it will dynamically generate the "pages" so that there are approximately `per_page` objects per page.
By dynamically generating the letter ranges, you avoid having too many objects in some letter ranges and too few in some. If your list is heavy on one end of the letter range, there will be more pages for that range.
It splits the pages on letter boundaries, so not all the pages will have exactly `per_page` objects. However, it will decide to overflow or underflow depending on which is closer to `per_page`.
**NamePaginator Arguments**:
`object_list`: A list, dictionary, QuerySet, or something similar.
`on`: If you specified a QuerySet, this is the field it will paginate on. In the example below, we're paginating a list of Contact objects, but the `Contact.email` string is what will be used in filtering.
`per_page`: How many items you want per page.
**Examples:**
>>> paginator = NamePaginator(Contacts.objects.all(), \
... on="email", per_page=10)
>>> paginator.num_pages
4
>>> paginator.pages
[A, B-R, S-T, U-Z]
>>> paginator.count
36
>>> page = paginator.page(2)
>>> page
'B-R'
>>> page.start_letter
'B'
>>> page.end_letter
'R'
>>> page.number
2
>>> page.count
8
In your view, you have something like:
contact_list = Contacts.objects.all()
paginator = NamePaginator(contact_list, \
on="first_name", per_page=25)
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
try:
page = paginator.page(page)
except (InvalidPage):
page = paginator.page(paginator.num_pages)
return render_to_response('list.html', {"page": page})
In your template, have something like:
{% for object in page.object_list %}
...
{% endfor %}
<div class="pagination">
Browse by title:
{% for p in page.paginator.pages %}
{% if p == page %}
<span class="selected">{{ page }}</span>
{% else %}
<a href="?page={{ page.number }}">
{{ page }}
</a>
{% endif %}
{% endfor %}
</div>
It currently only supports paginating on alphabets (not alphanumeric) and will throw an exception if any of the strings it is paginating on are blank. You can fix either of those shortcomings pretty easily, though.
**UPDATE**: A more complete example is up on [GitHub](http://github.com/henriklied/django-twitter-oauth/tree/master)
Based around Simon Willison's [Fire Eagle oAuth](http://www.djangosnippets.org/snippets/655/), this will allow you to develop Twitter oAuth applications (…that is – if you're in the closed beta)
Most of the time when I need to iterate over Whatever.objects.all() in a shell script, my machine promptly reminds me that sometimes even 4GB isn't enough memory to prevent swapping like a mad man, and bringing my laptop to a crawl. I've written 10 bazillion versions of this code. Never again.
**Caveats**
Note that you'll want to order the queryset, as ordering is not guaranteed by the database and you might end up iterating over some items twice, and some not at all. Also, if your database is being written to in between the time you start and finish your script, you might miss some items or process them twice.
This snippet is based on [#748](http://www.djangosnippets.org/snippets/748/).
Adds filtering by first char (alphabetic style) of values in the admin
filter sidebar. The example below results in this filter:
By name that starts with
All
A
B
G
M
X
urls.py example (only for register the filter):
import <your project>.admin.filterspecs
models.py example:
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=40)
name.alphabetic_filter = True
admin.py example:
class Admin:
list_filter = ['name']
This is the approach I've taken to access instances of child models from their parent. Functionally it's very similar to snippets [1031](http://www.djangosnippets.org/snippets/1031/) and [1034](http://www.djangosnippets.org/snippets/1034/), but without the use of `django.contrib.contenttypes`.
Usage:
class Post(ParentModel):
title = models.CharField(max_length=50)
objects = models.Manager()
children = ChildManager()
def __unicode__(self):
return self.title
def get_parent_model(self):
return Post
class Article(Post):
text = models.TextField()
class Photo(Post):
image = models.ImageField(upload_to='photos/')
class Link(Post):
url = models.URLField()
In this case, the `Post.children` manager will return a queryset containing instances of the appropriate child model, rather than instances of `Post`.
>>> Post.objects.all()
[<Post: Django>, <Post: Make a Tumblelog>, <Post: Self Portrait>]
>>> Post.children.all()
[<Link: Django>, <Article: Make a Tumblelog>, <Photo: Self Portrait>]
simple middleware and context processor for session-based messaging with types
Heavily inspired by patches on ticket 4604. Differs in that in this a notification
has type.
Installation:
* add notifications.NotificationMiddleware to MIDDLEWARE_CLASSES
* and notifications.notifications to TEMPLATE_CONTEXT_PROCESSORS
That assumes notifications.py is on pythonpath. If notifications.py lives in
your project dir, prefix those with '(projectname).'
Example use:
* request.notifications.create('Some bland information message.')
* request.notifications.create('Some more exciting error message.', 'error')
Example template code:
`{% if notifications %}
<ul id="notifications">
{% for notification in notifications %}<li class="{{ notification.type }}">{{ notification.content }}</li>
{% endfor %}
</ul>
{% endif %}`
[rendered example](http://traviscline.com/blog/2008/08/23/django-middleware-session-backed-messaging/)
"Make fixture" command. Highly useful for making test fixtures.
Use it to pick only few items from your data to serialize, restricted by primary keys.
By default command also serializes foreign keys and m2m relations.
You can turn off related items serialization with `--skip-related` option.
How to use:
python manage.py makefixture
will display what models are installed
python manage.py makefixture User[:3]
or
python manage.py makefixture auth.User[:3]
or
python manage.py makefixture django.contrib.auth.User[:3]
will serialize users with ids 1 and 2, with assigned groups, permissions and content types.
python manage.py makefixture YourModel[3] YourModel[6:10]
will serialize YourModel with key 3 and keys 6 to 9 inclusively.
Of course, you can serialize whole tables, and also different tables at once, and use options of dumpdata:
python manage.py makefixture --format=xml --indent=4 YourModel[3] AnotherModel auth.User[:5] auth.Group
This creates a fixture in the form of a python script.
Handles:
1. `ForeignKey` and `ManyToManyField`s (using python variables, not IDs)
2. Self-referencing `ForeignKey` (and M2M) fields
3. Sub-classed models
4. `ContentType` fields
5. Recursive references
6. `AutoField`s are excluded
7. Parent models are only included when no other child model links to it
There are a few benefits to this:
1. edit script to create 1,000s of generated entries using `for` loops, python modules etc.
2. little drama with model evolution: foreign keys handled naturally without IDs, new and removed columns are ignored
The [runscript command by poelzi](http://code.djangoproject.com/ticket/6243), complements this command very nicely! e.g.
$ ./manage.py dumpscript appname > scripts/testdata.py
$ ./manage.py reset appname
$ ./manage.py runscript testdata
based on Snippet [799](http://www.djangosnippets.org/snippets/799/) but added code inspection capabilities. Credit goes to django-logging for the actual inspection code.
Got the idea from the [This Week in Django](http://blog.michaeltrier.com/2008/6/18/this-week-in-django-26-2008-06-16) Podcast ;)
This adds the filename, lineno, functionname and the actual python-code line which caused a sql statement to be executed.
Note that i am adding keys to 'connection.queries' dict on request, which may be dangerous, so use with care!
The code inspection functionality can be toggled via FRAME_INSPECT.
This tiny template filter saves you the tedious test "if this variable is set, print this text based on this variable".
'verbose' filter takes one parameter : a string containing '%s' which is a placeholder for the value to test. Check those examples :
* Replace this :
{% if name %}
Hello {{ name }}, this is a dummy text
{% endif %}
* By this :
{{ name|verbose:"Hello %s this is a dummy text" }}
This is also usefull for HTML :
{{ image|verbose:"<img src=\"%s\" />" }}
Simply adds an attribute `is_ajax` to a request object, indicating if the request was made via Ajax. Allows you to reuse a lot of POST processing view code to which you'd like to progressively add Ajax:
`if request.is_ajax: return JsonResponse(some_json)`
`else: return render_to_response('some_template.html')`
This is the view-code to export a database-dump (hardcoded for mysql) or a media_root dump via the admin interface.
just add 2 urls patterns to call the views and a small template with a simple form to send a http-post to the views.
Note: The downloads are sort of streaming. I have successfully exportet a 2GB media_root as tar-ball without major increase of ram-usage of the django-process.
This is a little improvement to the [idea](http://www.djangosnippets.org/snippets/540/) from sheats a few days ago.
I like it over the previous solutions because it doesn't involve doing anything other than running `./manage.py shell` inside your project directory. You don't have to create any files anywhere or remember to call anything, and `ipython` still works fine outside of a Django project.
Throw this code in `~/.ipython/ipy_user_conf.py` (`ipythonrc` has apparently been deprecated).
Put this code somewhere in one of your INSTALLED_APPS `__init__.py` file. This code will replace the django.template.loader.get_template with cached version. Standard get_template function from django reads and parses the template code every time it's called. This version calls (if DEBUG set to False) it only once per template. After that it gets a Template object from template_cache dictionary. On django http server with template code like that:
{% extends "index.html" %}
{% block content %}
{% if form.has_errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<form method="post" action=".">
<table>
<tr><td><label for="id_username">Username:</label></td><td>{{ form.username }}</td></tr>
<tr><td><label for="id_password">Password:</label></td><td>{{ form.password }}</td></tr>
</table>
<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
{% endblock %}
ab -n 100 on mac os x 10.5 core 2 duo 2 ghz with 2 GB of RAM gives
forge-macbook:~ forge$ ab -n 100 http://127.0.0.1:8000/login/
This is ApacheBench, Version 2.0.40-dev <$Revision: 1.146 $> apache-2.0
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Copyright 2006 The Apache Software Foundation, http://www.apache.org/
Benchmarking 127.0.0.1 (be patient).....done
Server Software: WSGIServer/0.1
Server Hostname: 127.0.0.1
Server Port: 8000
Document Path: /login/
Document Length: 934 bytes
Concurrency Level: 1
Time taken for tests: 0.432934 seconds
Complete requests: 100
Failed requests: 0
Write errors: 0
Total transferred: 120200 bytes
HTML transferred: 93400 bytes
Requests per second: 230.98 [#/sec] (mean)
Time per request: 4.329 [ms] (mean)
Time per request: 4.329 [ms] (mean, across all concurrent requests)
Transfer rate: 270.25 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 0.0 0 0
Processing: 3 3 1.5 4 12
Waiting: 3 3 1.2 3 12
Total: 3 3 1.5 4 12
Percentage of the requests served within a certain time (ms)
50% 4
66% 4
75% 4
80% 4
90% 4
95% 5
98% 10
99% 12
100% 12 (longest request)
without template caching, and
forge-macbook:~ forge$ ab -n 100 http://127.0.0.1:8000/login/
This is ApacheBench, Version 2.0.40-dev <$Revision: 1.146 $> apache-2.0
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Copyright 2006 The Apache Software Foundation, http://www.apache.org/
Benchmarking 127.0.0.1 (be patient).....done
Server Software: WSGIServer/0.1
Server Hostname: 127.0.0.1
Server Port: 8000
Document Path: /login/
Document Length: 934 bytes
Concurrency Level: 1
Time taken for tests: 0.369860 seconds
Complete requests: 100
Failed requests: 0
Write errors: 0
Total transferred: 120200 bytes
HTML transferred: 93400 bytes
Requests per second: 270.37 [#/sec] (mean)
Time per request: 3.699 [ms] (mean)
Time per request: 3.699 [ms] (mean, across all concurrent requests)
Transfer rate: 316.34 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 0.0 0 0
Processing: 3 3 0.9 3 9
Waiting: 2 3 0.9 3 8
Total: 3 3 0.9 3 9
Percentage of the requests served within a certain time (ms)
50% 3
66% 3
75% 3
80% 3
90% 3
95% 5
98% 8
99% 9
100% 9 (longest request)
with caching enabled.
In both cases DEBUG is set to False.
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.