I had a problem: too many fetches from the DB.
So, how to reduce load on the database without major changes to the code?
Cache Manager is the answer. I've managed to reduce number of DB hits as much as 80% in some cases (dictionaries, complex relations). It is using standard cache mechanisms. I'm using it with mathopd.
This is a very simple solution, instead of standard Manager, put this in your model definition as:
`objects = CacheManager()`
Then everythere elase in the code instead of all() or get(...) call all_cached() or get_cached().
I've kept original methods intact, to have an dual access, when you really, really must have frest data from the DB, and you can't wait for cache to expire.
This is much easier to work with, then manually getting fetched data from the cache.No change to your existing code 9except model) and voila!
Additionally if you have some data, you would like to store with your serialized object (e.g. related data, dynamic dictionaries), you can do this in the model method '_init_instance_cache').
Drop me an email if you find this useful. :)
I use this to integrate a google map in a form renderd by newforms. If someone click on the map and set a icon, the Latitude and Longitude data goes into the 2 form fields.
You need to generate a google API key (http://www.google.com/apis/maps/signup.html) for the GOOGLE_KEY variable.
With this middleware in place (add it to the MIDDLEWARE_CLASSES in your settings) you can pass a request to the model via a pre_save method on the model.
I'm not sure if it is an improvement over the [threadlocals method] (http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser) but it may be an alternative that can be improved upon?
class MyModel(models.Model):
name = models.CharField(max_length=50)
created = models.DateTimeField()
created_by = models.ForeignKey(User, null=True, blank=True)
def pre_save(self, request):
if not self.id:
self.created_by = request.user
This is a simple template tag to create Tag Clouds. Based on the number of Posts (change the model_name according to your schema), Tags are provided different size ( most number of posts => most popular => and hence the largest.
We create a property called cloudsize for each tag, which is an integer between minsize and maxsize.
Check the example of sample template use here http://www.djangosnippets.org/snippets/472/
**Explanation:**
I think this shortcut can be util for who uses JSON many times and does not want to write same code everytime.
**Setup:**
Saves the snippet as `myproject/utils.py` or add the code to some place in your project with same ends.
**Use in a view:**
from myproject.utils import render_to_json
from django.contrib.admin.models import User
def json_view(request):
admin_user = User.objects.get(username='admin')
return render_to_json(
'json/example.json',
locals(),
)
**Update:**
This code can be used as complement to [http://www.djangosnippets.org/snippets/154/](JsonResponse snippet) too.
**Explanations:**
- the series "is_*_of" was created 'cos it's easier write: `{% if 10|is_day_of:date and user %}` than write: `{% ifequal date.day 10 %}{% if user %}...`
- the series "inc/dec" is not complete, but can the extended to day, hour, minute, etc as you needs. It's util to inc 10 months since 05/31/2006 by example and get a 2007's date :)
**Setup:**
Insert the snippet into an_app/templatetags/datetimeutils.py.
**Use in template:**
`{% load datetimeutils %}` and use filters as following:
- `{{ 30|is_day_of:a_date_time_variable }}`
- `{{ 11|is_month_of:a_date_time_variable }}`
- `{{ 2006|is_year_of:a_date_time_variable }}`
- `{{ 58|is_minute_of:a_date_time_variable }}`
- `{{ 23|is_hour_of:a_date_time_variable }}`
- `{{ a_date_time_variable|dec_year:2 }}`
- `{{ a_date_time_variable|dec_month:2 }}`
- `{{ a_date_time_variable|inc_year:2 }}`
- `{{ a_date_time_variable|inc_month:2 }}`
[The Session documentation](http://www.djangoproject.com/documentation/sessions/) rightly warns of the dangers of putting a session ID into a query string. Sometimes, however, you have to do it - perhaps your client has mandated support for browsers with cookies disabled, or perhaps (as in my case) you're just dealing with a slightly broken client browser.
This middleware pulls a session ID out of the query string an inserts it into the cookies collection. You'll need to include it in your MIDDLEWARE_CLASSES tuple in settings.py, *before* the SessionMiddleware.
*Please* read my [full blog post](http://www.stereoplex.com/two-voices/cookieless-django-sessions-and-authentication-without-cookies) about for the dangers of doing this, and for full instructions and examples.
A Django image thumbnail filter, adapted from code by [Batiste Bieler](http://batiste.dosimple.ch/blog/2007-05-13-1/).
This updated version drops support for cropping and just rescales. You should use it in your templates like this:
`<img src='{{ MEDIA_URL }}{{ image.get_image_filename|thumbnail:"300w,listingimages" }}' alt="{{ image.title }}" title="{{ image.title }}" />`
This will produce a 300-pixel wide thumbnail of image, with the height scaled appropriately to keep the same image aspect ratio. 'listingimages' is the path under your MEDIA_ROOT that the image lives in - it'll be whatever upload_to is set to in your ImageField.
If instead you wanted an image scaled to a maximum height of 140px, you'd use something like this:
`<img src='{{ MEDIA_URL }}{{ image.get_image_filename|thumbnail:"140h,listingimages" }}' alt="{{ image.title }}" title="{{ image.title }}" />`
Note the number has changed from 300 to 140, and the trailing letter from 'w' to 'h'.
Please leave feedback and bug reports on [my blog, Stereoplex](http://www.stereoplex.com/two-voices/a-django-image-thumbnail-filter). I've only lightly tested this so you'll probably find something!
I thought it would be a neat idea to use the PyCrust shell for interacting with my models, instead of using the plain old shell.
So what I did, is take a copy of the file:
django/core/management/commands/shell.py
Altered it, and saved it as:
django/core/management/commands/pycrust.py
For this to work, you should have pycrust installed (python-wxtools in ubuntu) and save this snippet as django/core/management/commands/pycrust.py, then run as follows:
./manage.py pycrust
instead of
./manage.py shell
Have fun!
**Usuage:**
{{ comment.comment|truncatechars:20 }}
**Why to use:**
First of all, my english isn´t the best. I hope you will understand my text anyways :)
Ok, I had a problem with some "kiddies" posting huge comments like
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaahhhhhhhhhhhhhhhhhhh this game rooooooooooocks!!!!!!!!!!!!!!!!".
Django has no function to "kill" that huge words within a string. So I´ve coded this little peace and hope that someone could use it.
Greets from Germany,
Aveal
http://www.onlinewars.eu
The solution is based on [dballanc's snippet](http://www.djangosnippets.org/snippets/420/).
Can easily be combined with any of the [SQL tracing solutions](http://www.djangosnippets.org/tags/debug/).
You might want to run a separate logging server and redirect your logs there. Please refer to the [logging reference manual](http://docs.python.org/lib/module-logging.html).
Simple middelware that listens for redirect responses, store the request's query log in the session when it finds one, and starts the next request's log off with those queries from before the redirect.
I wanted to have the possibility to use a wiki-like markup style in my flatpages for various purposes (embedding images, quoting, etc.)
After a few dead ends I came up with this, which is quite nice I think.
> It basically takes a named tag, loads the corresponding template, passes in all arguments, renders the template and replaces the named tag with the result.
*The markup looks like this:*
> [[example:value to pass|option1=somevalue option2=values can have spaces too! without having to put them in quotes option3=some other value]]
*This results in:*
* Filter tries to load wiki/wiki_example.html
* If it is loaded, it passes an WikiElement containing the value and the options to the template, renders it and replaces the tag with the rendered template
*In the "wiki/wiki_example.html" template you can use it like this:*
{{param.value}}
{{param.opts.option1}}
Or loop over param.opts.iteritems.
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.