Ever wanted to add a link or two at the end of a row in a model's change list? Say you had a model for people and a model for registrations or blog posts and you want to modify the people change list so it has a link to, say all of the registrations or blog posts for the person.
Well, Django provides half of the solution already in that the example registration change_list already handles the display of all registrations tied to that person. For example, the url `/admin/registrations/registration/?person__id__exact=121` gets you to a filtered list of registrations for the person with the id of 121. This is the same url used if you use list_filter in your model definition (though setting list_filter is not required for what we're doing).
Okay, so to add a link to the end of each person row in the change list, you need to create a template tag similar to "person_result_list" in the code. There, I've given an example that adds two links. Each dictionary in additional_links needs to have at least a text, sortable, and url_template attribute. The text attribute is what will display as the header to the column. url_template will be fed the id of the row object (in this example, a person id), which you can use to construct the link for each row. You could extend this if you wish, though all I ever need is the id.
And the last step is to use your new template tag in a modified change_list.html in place of the default result_list tag. The example at the bottom of the code shows an example usage of the tag.
Hope this makes sense and is helpful to someone!
Flash message add-on for Django. Uses sessions. Behavior is such that you set a flash message in a view. That message is stored in the sesssion. Then whenever it is that the message gets displayed, it is removed from the session (never to be heard from again)
**Installation:**
In your settings, enable the following items.
TEMPLATE_CONTEXT_PROCESSORS
django.core.context_processors.request
MIDDLEWARE_CLASSES
django.contrib.sessions.middleware.SessionMiddleware
Then put it into a file called flash.py in your templatetags directory.
**Usage:**
It's pretty simple. Do something like this in your view ..
>>>request.session['flash_msg'] = 'Your changes have been save'
>>>request.session['flash_params'] = {'type': 'success'}
And maybe put something like this in your template
{% load flash %}
{% flash %}
<h2>{{ params.type }}</h2>
{{ msg }}
{% endflash %}
It also support a flash template, you can specify a file
FLASH_TEMPLATE in your settings file and then that file will be rendered with msg and params as available variable.
Usage for this would simply be `{% flash_template %}` and then you gotta make a template file that does whatever you like.
Outside of that just be aware you need the Django session middleware and request context installed in your app to use this.
Given an item and a list, check if the item is in the list
-----
item = 'a'
list = [1, 'b', 'a', 4]
-----
{% ifinlist item list %}
Yup, it's in the list
{% else %}
Nope, it's not in the list
{% endifinlist %}
I have not extensively test this yet. But working for templates with embedded images.
If you want to use Django template system use `msg` and optionally `textmsg` as template context (dict) and define `template` and optionally `texttemplate` variables.
Otherwise msg and textmsg variables are used as html and text message sources.
If you want to use images in html message, define physical paths and ids in tuples.
(image paths are relative to MEDIA_ROOT)
example:
images=(('email_images/logo.gif','img1'),('email_images/footer.gif','img2'))
use them in html like this:
`<img src="cid:img1"><br><img src="cid:img2">`
stripogram and feedparser modules are used for extract plain text from html message source.
If you are going to define text partition explicitly, than you can comment out line 10,11 and 48.
This filter will display the time as word(s) indicating roughly the time of day ("Morning", "Afternoon", "Evening", etc). For example, the following template snippet:
Posted in the {{ post.date|fuzzy_time }} of {{ post.date|date:"F j, Y"} }}.
will result in the following (assuming `post.date == datetime.datetime(2007, 6, 13, 20, 57, 55, 765000)`):
Posted in the evening of June 13, 2007.
The terms used and breakpoints (hours only) can be rather arbitrary so you may want to adjust them to your liking. See the docs for [bisect][] for help in understanding the code. Just remember you should have one less breakpoint than periods and the first breakpoint falls at the end of the first period. The idea was inspired by [Dunstan Orchard][1], although the code is *very* different (php case statement). He uses quite a bit more periods in a day, so you might want to take a look.
[bisect]: http://docs.python.org/lib/module-bisect.html
[1]: http://www.1976design.com/blog/archive/2004/07/23/redesign-time-presentation/
As an alternative to using forms rendered with the
default hard-coded html, this factory function will
take a template name as argument, and return a Form class based on django.newforms.BaseForm, which will
render each form field using the supplied template.
As an example, I'm using this class as follows in one
project (slightly edited with respect to project and
app names):
# Get a form class which renders fields using a given template
CustomForm = proj.utils.makeTemplatedForm(template="app/formfield.html")
# Get base form class for the details model
BaseAppForm = forms.form_for_model(models.AppDetail, form=CustomForm)
using this template:
{% if errors %}
<ul class="errorlist">
{% for error in errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
{% if field.required %}<span class="required">*</span>{% endif %}{{ text }}
{{ help_text }}
This is tag similar to *timesince* and *timeuntil*, which work great until you starting giving timesince dates in the future or timeuntil dates in the past. Timedelta tag will humanize output correctly for both future and past dates using *now* as a default reference date (or a specified reference date as argument)
now = Apr 27 2007
futuredate = May 5 2007
pastdate = Jan 5 2007
{{ futuredate|timedelta }} will output "in 1 week, 1 day"
{{ pastdate|timedelta }} will output "3 months, 2 weeks ago"
Simple template filter to encode a variable to JSON format
Usage:
{% load json_filters %}
{% block content %}
<script type="text/javascript"><![CDATA[
var items = {{ items|jsonify }};
]]></script>
{% endblock %}
I'm using JsonResponse for the views but I also want to have preloaded JSON data into the page output
A slightly improved version of [snippet #195](/snippets/195/) which keeps the logic but makes use of the `simple_tag` decorator to drastically simplify the code.
For an alternative to this sort of tag, check out the media context processor in my [template_utils app](http://code.google.com/p/django-template-utils/).
This a small but very handy view that gives you a convenient direct access to your templates.
Now suppose you saved the snippet under `misc.py`, it's critical to add this snippet (or a similar one, once you get the idea) to your `urls.py`:
if settings.DEBUG:
# Direct Templates
urlpatterns += patterns('misc',
(r'^template/(?P<path>.*)$', 'direct_to_template', {'template': '%(path)s'}),
)
Now you are able to access any of your templates, in different directories by specifying their path after `template/`. e.g., http://example.com/template/news/index.html
Of course you can change it as you want, you can also add other values to the dict argument, the only required key is `'template'`. The whole dict is made available in the template as a context.
All GET parameters are made available in the template too. So `http://example.com/template/news/index.html?title=Testing Title` will make the `{{ title }}` var available in your template. So you can substitute basic variables quickly.
This is was inspired by [django.views.generic.simple.direct_to_template](http://www.djangoproject.com/documentation/generic_views/#django-views-generic-simple-direct-to-template)
Returns an absolute URL pointing to the given media file.
The first argument is the path to the file starting from MEDIA_ROOT.
If the file doesn't exist, empty string '' is returned.
For example if you have the following in your settings:
MEDIA_URL = 'http://media.example.com'
then in your template you can get the URL for css/mystyle.css like this:
{% media 'css/mystyle.css' %}
This URL will be returned: http://media.example.com/css/style.css.
Returns 'Morning', 'Afternoon', or 'Evening' in the local timezone (specified in settings). Required pytz. 0000-1200 considered morning, 1200-1800 considered afternoon, 1800-0000 considered evening.
dirt and simple template filter to convert a number to its roman value. taken from dive into python http://www.diveintopython.org/unit_testing/stage_5.html
It's been a while, but I think I made this by copying and pasting the default {% if %} tag and modifying it. Does what it says, lets you test for inclusion in a list, in templates, like so: {% ifin item list %}.