Similar to [Profiling Middleware](http://www.djangosnippets.org/snippets/186/), but uses cProfile instead of hotshot.
Append ?prof to the URL to see profiling output instead of page output.
This is a little snippet that you can use to make your Django newforms dynamic at runtime. You can define an arbitrary number of fields of the form without loosing newforms capibilites.
You can render the form dynamically be "misusing" the "help_text" attribute of the form fields (Every form field allows the definition of this attribute). This way you can search for changes in the help_text of every field and render the form accordingly.
The form itself is dynamically defined in the view.
The form state can be saved in a Django Session Variable (specifically for Linux users with a process-based Apache Server), so that you can rebuild and verify a submitted form.
[See blog post](http://paltman.com/2008/04/11/keeping-contenttypes-and-permissions-updated-without-syncdb/)
You can put this script in the root of your project and run after deploying updates in your production environment.
Use these tags and filter when you're rolling your own search results. This is intended to be a whole templatetags module. I keep it in my apps as `templatetags/search.py`. These should not be used to perform search queries, but rather render the results.
### Basics
There are three functions, each has both a tag *and* a filter of the same name. These functions accept, at a minimum, a body of text and a list of search terms:
* **searchexcerpt**: Truncate the text so that each search term is shown, surrounded by some number of words of context.
* **highlight**: Wrap all found search terms in an HTML span that can be styled to highlight the terms.
* **hits**: Count the occurrences of the search terms in the text.
The filters provide the most basic functionality as described above, while the tags offer more options as arguments, such as case sensitivity, whole word search, and saving the results to a context variable.
### Settings
Defaults for both the tags and filters can be changed with the following settings. Note that these settings are merely a convenience for the tags, which accept these as arguments, but are necessary for changing behavior of the filters.
* `SEARCH_CONTEXT_WORDS`: Number of words to show on the left and right of each search term. Default: 10
* `SEARCH_IGNORE_CASE`: False for case sensitive, True otherwise. Default: True
* `SEARCH_WORD_BOUNDARY`: Find whole words and not strings in the middle of words. Default: False
* `SEARCH_HIGHLIGHT_CLASS`: The class to give the HTML span element when wrapping highlighted search terms. Default: "highlight"
### Examples
Suppose you have a list `flatpages` resulting from a search query, and the search terms (split into a list) are in the context variable `terms`. This will show 5 words of context around each term and highlight matches in the title:
{% for page in flatpages %}
<h3>{{ page.title|highlight:terms }}</h3>
<p>
{% searchexcerpt terms 5 %}
{{ page.content|striptags }}
{% endsearchexcerpt %}
</p>
{% endfor %}
Add highlighting to the excerpt, and use a custom span class (the two flags are for case insensitivity and respecting word boundaries):
{% highlight 1 1 "match" %}
{% searchexcerpt terms 5 1 1 %}
{{ page.content|striptags }}
{% endsearchexcerpt %}
{% endhighlight %}
Show the number of hits in the body:
<h3>{{ page.title }}
(Hits: {{ page.content|striptags|hits:terms }})
</h3>
All tags support an `as name` suffix, in which case an object will be stored in the template context with the given name; output will be suppressed. This is more efficient when you want both the excerpt and the number of hits. The stored object depends on the tag:
* **searchexcerpt**: A dictionary with keys "original" (the text searched), "excerpt" (the summarized text with search terms), and "hits" (the number of hits in the text).
* **searchcontext**: A dictionary with keys "original", "highlighted", and "hits", with obvious values.
* **hits**: Just the number of hits, nothing special.
Getting both the hits and the excerpt with "as":
{% searchexcerpt terms 3 as content %}
{{ page.content|striptags }}
{% endsearchexcerpt %}
<p>Hits: {{ content.hits }}<br>{{ content.excerpt }}</p>
### More
For more examples see [Brian Beck's Text Adventure][announcement].
[announcement]: http://blog.brianbeck.com/post/29707610
Creates a template tag called "split_list" which can split a list into chunks of a given size. For instance, if you have a list 'some_data', and you want to put it into a table with three items per row, you could use this tag:
{% split_list some_data as chunked_data 3 %}
Given a some_data of [1,2,3,4,5,6], the context variable 'chunked_data' becomes [[1,2,3],[4,5,6]]
This is useful for creating rows of equal numbers of items.
Thanks to the users of #django (pauladamsmith, Adam_G, and ubernostrum) for advice and pointers, thanks to Guyon Morée for writing the chunking recipe that this tag is based on.
This recipe raises an exception if there is an invalid variable in the template.
See [#6766](http://code.djangoproject.com/ticket/6766)
Note: I don't need this snippet any more, since I don't use the template language any more. For
my projects using only python is better (complex logic, simple layout).
ModelChoiceField allows you to use filtered queries to simplify your forms. This is great for adding objects but can fall down when you edit an existing object and the original query no longer contains the referenced field (e.g. I like to use an "active" field in several objects).
The fix is simply to include an extra param: Q(pk=object_id). You have to do this in the __init__ method to get the object_id.
A nice thing about this is that it works for ModelForms as well as custom Forms.
Decorator to make a view only accept requests from AJAX calls. Usage::
@require_xhr()
def my_view(request):
# Returns data
# ...
by [skam](http://skam.webfactional.com/)
Some template tags/filter for working with query strings in templates.
Examples:
{% load qstring %}
{% qstring %} # Prints current request's query string
{% qstring as current_qstring %} # Same but goes to context
{{ current_qstring|qstring_del:"key1" }} # Deletes all key1 values
{{ current_qstring|qstring_del:"key1&key2" }} # Deletes all key1 and key2values
{{ current_qstring|qstring_set:"key1=1&key2=2" }} # Deletes all old key1 and key2 values and adds the new values.
register any python function as a tag with an optional name.
usage:
in templatetags:
@function_tag()
def foo(arg):
return do_something(arg)
in template:
{% foo arg %} or {% foo arg as variable %}{{ variable.bar }}
The script that can be used to profile any Django-powered web-site and find how many SQL-queries are used per page, how heavy html-pages are, etc.
To use the the script it's enough to put django-profile.py somewhere in PYTHONPATH and call it from the directory that holds projects' settings.py.
For more info and examples please see:
[www.mysoftparade.com/blog/django-profile-sql-performance/](http://www.mysoftparade.com/blog/django-profile-sql-performance/)
This Middleware is to log users out after a certain amount of time has passed. You'll want to add AUTO_LOGOUT_DELAY to your settings.py, set to a number of minutes after which a user should be logged out.
It adds the key 'last_touch' to the session, you'll want to change that if you happen to be using that already.
This Update adds requested support for self referential fields.
This is useful if you need to compute and store potentially hundreds or thousands of objects and relationships quickly. To perform the inserts it will hit the database 1 plus N/100 times per affected table and where N is the number of rows to be inserted. It will use INSERT or LOAD DATA INFILE on MySQL.
Run this on your test database first and make sure all of your field defaults and null values are set appropriately as you could attempt to insert a NULL where it isn't allowed and end up with a partial insert.
This code is reasonably well tested and has been used for database pre-loading and operations on live sites.
My test suite, however, is focused on my own use cases. Any input, i.e. failures, for creating more tests would be appreciated.
Lots of Details in the Doc String.
Currently only MySQL, however there is some crude skeleton code to support other databases.
Adds a shortcut to edit releated objects right/ForeignKey fields.
an edit symbol will be shown right next to the "add annother" link on all select boxes,
with opens the releated object currently selected in a popup window.
**depends on jquery**
Add this to the head of "templates/admin/base.html".
you may need to add
`<script type="text/javascript" src="/path/to/jquery.js"></script>`
before it
Have you ever needed to customize permissions, for example, allow only some fields for editing by some group of users, display some fields as read-only, and some to hide completely?
FieldLevelPermissionsAdmin class does this for newforms-admin branch.
Not tested well yet (>100 LOC!).
You typically would like to use it this way:
class MyObjectAdmin(FieldLevelPermissionsAdmin):
def can_view_field(self, request, object, field_name):
"""
Boolean method, returning True if user allowed to view
field with name field_name.
user is stored in the request object,
object is None only if object does not exist yet
"""
...your code...
def can_change_field(self, request, object, field_name):
"""
Boolean method, returning True if user allowed to
change field with name field_name.
user is stored in the request object,
object is None only if object does not exist yet
"""
...your code...
def queryset(self, request):
"""
Method of ModelAdmin, override it if you want to change
list of objects visible by the current user.
"""
mgr = self.model._default_manager
if request.user.is_superuser:
return mgr.all()
filters = Q(creator=request.user)|Q(owner=request.user)
return mgr.filter(filters)
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.