Inspired by http://www.djangosnippets.org/snippets/159/
This context processor provides a new variable {{ sqldebug }}, which can
be used as follows:
{% if sqldebug %}...{% endif %}
{% if sqldebug.enabled %}...{% endif %}
This checks settings.SQL_DEBUG and settings.DEBUG. Both need to be True,
otherwise the above will evaluate to False and sql debugging is considered
to be disabled.
{{ sqldebug }}
This prints basic information like total number of queries and total time.
{{ sqldebug.time }}, {{ sqldebug.queries.count }}
Both pieces of data can be accessed manually as well.
{{ sqldebug.queries }}
Lists all queries as LI elements.
{% for q in sqldebug.queries %}
<li>{{ q.time }}: {{ q }}</li>
{% endfor %}
Queries can be iterated as well. The query is automatically escaped and contains
<wbr> tags to improve display of long queries. You can use {{ q.sql }} to access
the unmodified, raw query string.
Here's a more complex example. It the snippet from:
http://www.djangosnippets.org/snippets/93/
adjusted for this context processor.
{% if sqldebug %}
<div id="debug">
<p>
{{ sqldebug.queries.count }} Quer{{ sqldebug.queries|pluralize:"y,ies" }}, {{ sqldebug.time }} seconds
{% ifnotequal sql_queries|length 0 %}
(<span style="cursor: pointer;" onclick="var s=document.getElementById('debugQueryTable').style;s.display=s.display=='none'?'':'none';this.innerHTML=this.innerHTML=='Show'?'Hide':'Show';">Show</span>)
{% endifnotequal %}
</p>
<table id="debugQueryTable" style="display: none;">
<col width="1"></col>
<col></col>
<col width="1"></col>
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">SQL</th>
<th scope="col">Time</th>
</tr>
</thead>
<tbody>
{% for query in sqldebug.queries %}<tr class="{% cycle odd,even %}">
<td>{{ forloop.counter }}</td>
<td>{{ query }}</td>
<td>{{ query.time }}</td>
</tr>{% endfor %}
</tbody>
</table>
</div>
{% endif %}
This is based on [Snippet 161](/snippets/161/)
It marks duplicated SQL queries.
To avoid duplicates read:
[Caching and Queryset](http://www.djangoproject.com/documentation/db-api/#caching-and-querysets)
Sept. 07: Updated for current trunk: 'response' behaves like 'response.header'
22. October '07: Log into directory.
This snippet is based on djangos urlize filter. It converts http:// links to youtube into youtube-embed statements, so that one can provide a simple link to a youtube video and this filter will embed it. I used it for a fun blog app.
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 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.
Simple anti-spam field which will cause the form to raise a `ValidationError` if the value in this field changes. Displays as a CSS hidden `<input type="text" />` field.
If you specify a `class` in the `attrs` of the widget, the default `style="display:none;"` won't be rendered with the widget so that you can use a predefined CSS style to do your hiding instead. You can also cause the widget to be wrapped in an html comment to ensure it is not visible to the end user:
class EmailForm(Form):
email = EmailField()
website = HoneypotField(widget=HoneypotWidget(
attrs={'class':'fish'}, html_comment=True))
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 python script](http://www.djangosnippets.org/snippets/127/)
Newforms are made to make any kind of customizations easy. Sometimes standard methods of rendering HTML/XML/other content of the django.newforms is not enough to completely satisfy all web design needs so you may want to present forms in own templates.
Using templates to render output as HTML or XML is straighforward, and in many cases easier then using standard approach.
Step by step usage guide:
1. Create file in your project yourproject/utils/newforms.py and place Class TemplatedForm there
2. Create newforms subdirectory in templates dir, and post 2 templates there (form.html, field.html) from the documentation code for TemplatedForm class
3. Inherit from TemplatedForm in your form class to use this form.
This is a minor modification to [Upload a file using newforms](http://www.djangosnippets.org/snippets/95/) as posted by [mboersma](http://www.djangosnippets.org/snippets/95/).
I altered the ZipUploadForm by removing lines 33 - 34:
if 'zip_file' in self.clean_data:
zip_file = self.clean_data['zip_file']
and adding a return statement to clean_zipfile, which returns the validated zip file. I also added the line:
zip_file.clean = clean_zipfile
so that when the full_clean() in called on the form, clean_zipfile will automatically run.
All other code (the view & template) remain the same.
** Disclaimer **
I'm not *that* familiar with newforms, so please forgive me if some the explanation as to why this works is incorrect ;) Who knows, maybe the first guy had it right.
Use this code to generate downloadable [vCard][] objects. See the [VObject docs][1] for more details on the API.
[1]: http://vobject.skyhouseconsulting.com/
[vcard]: http://en.wikipedia.org/wiki/VCard
Using newforms you can create forms from existing models easily and automatically with either `form_for_model(class)` or `form_for_instance(instance)`. Usually the automagically generated form fields are sufficient; however, sometimes you need to restrict selections in a choice field.
You can also set the default selection when instantiating the form. In this example, if `acct` is not contained in the 'account' field choices, the selection defaults to the first entry.
This example is probably not good practice when using `form_for_instance` because the existing value 'selection' of the choice field is lost and must be reset manually (see above).
This is part of the user-registration code used on this site (see [the django-registration project on Google Code](http://code.google.com/p/django-registration/) for full source code), and shows a couple of interesting tricks you can do with manager methods.
In this case there's a separate `RegistrationProfile` model used to store an activation key and expiration time for a new user's account, and the manager provides a couple of useful methods for working with them: `create_inactive_user` creates a new user and a new `RegistrationProfile` and emails an activation link, `activate_user` knows how to activate a user's account, and `delete_expired_users` knows how to clean out old accounts that were never activated.
Putting this code into custom manager methods helps a lot with re-use, because it means that this code doesn't have to be copied over into different views for each site which uses registration, and also makes more sense in terms of design, because these are methods which need to "know about" the model and work with it, and so they belong in a place close to the model.
This is a method from the custom manager for the Snippet model used on this site; the basic idea is to be able to ask for the top `n` "foo", where "foo" is something related to Snippet. For example, you can use `top_items('tag')` to get the top Tags ordered by how many Snippets are associated with them.
I have a feeling that I could get this down to one query, but haven't yet put in the time for it.
A template tag that includes a modified version of the GET query string. the query string can be manipulated by adding and removing fields. If a value is given that resolves to a context variable that the value of the variable is used. Based on [this snippet by dnordberg](http://djangosnippets.org/snippets/826/), but with the ability to use context and done in a cleaner manner, without the need to add an arbitrary template.
Use django_openid_auth from https://launchpad.net/django-openid-auth to authenticate your users with their Google Account.
This snippet will allow your users having a Google Account address as username to log in using it.
You're looking at the most-bookmarked snippets on the site; if you'd like to help useful snippets show up here, sign up for an account and you'll get your own bookmarks list.