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 code will add a thumbnail image to your Model's Admin list view. The code will also generate the thumb images, so the first view may be a little slow loading.
This assumes you have an **ImageField** in your Model called **image**, and the field's **upload_to** directory has a subdirectory called **tiny**. You then must add **"thumb"** to your Model's Admin **list_display**.
The thumbnail images are also linked to the full size view of the image.
I found this **VERY** useful... hope someone else does as well.
I recently got a form working via jQuery and Django. This was not easy for me to do and I thought I'd record my finding here.
The form submits via jQuery and the "form" plugin. Please visit jQuery's home page to find all those links.
This code handles:
* urls.py -- passing both normal and 'Ajax' urls to a view.
* views.py -- Handling both kinds of requests so that both normal and ajax submits will work.
* The HTML template with the script for submitting and some bling.
Error handling
===
I like to stay DRY so the idea of checking the form for errors in javascript *and* checking it in Django irks me. I decided to leave that up to Django, so the form submits and gets validated on the server. The error messages are sent back to the browser and then displayed.
This is a pretty straightforward bit of code for getting the most-commented objects of a particular model; just drop it into a custom manager for that model, and you should be good to go. Check the docstring for how to make it look at `Comment` instead of `FreeComment`.
Django's transition from oldforms to newforms is nearing. If you're using recent trunk source code from Django's subversion repository, you should start using newforms.
But there are still some rough edges as of today. File uploading seems to be one of them. (Adrian and other Django folks are well aware of this. Please don't bother them by asking "Are we there yet?")
The Django mailing lists and Google searching didn't turn up any best practices for this area of newforms, so I muddled through it and here's the result. I omit the urls.py code necessary to hook up the zip_upload method to a URL, but otherwise this should be complete.
And if I haven't loaded this with enough caveats...please be aware this code may be obsoleted soon.
This is a simple filter I use to display a list of links from a blog entry off in the sidebar ([example](http://www2.jeffcroft.com/blog/2007/feb/25/two-new-django-sites-both-source-available/)).
Requires beautifulsoup. Originally by [Nathan Borror](http://playgroundblues.com), tweaked slightly by me.
This jQuery javascript enables dynamic add/delete of rows in tabular inlines. It adds a "+" icon at the bottom of the inline to allow addition of new rows, and replaces the default delete checkbox with a "x" icon for deletion, giving you the possibility to add/delete rows instantly without reloading the page.
In addition, it gives you drag-n-drop ordering functionality with a named position model field using jQuery UI Sortable.
**Usage (see below for example):**
Just include the javascript on your admin page, together with jQuery, and it'll automatically affect all tabular inlines. Optionally, also include jQuery UI Sortable and an Integer field in your inline model named "position" (or whatever you set "position_field" to), which will automatically hide the position field and enable drag-n-drop sorting.
**Developed for:**
* jQuery 1.3.2
* jQuery UI 1.7.1
* Django trunk (tested in Django v1.0.2)
* (Might work with other versions with or without adjustments, but not tested)
**Settings (in top of javascript):**
* "position_field" is the name of an integer model field that is used for ordering the inline model. If left empty or not found, the drag-n-drop functionality is dropped. Defaults to "position".
* "add_link_html" for custom look of "add"-buttons. Defaults to Django's built-in "+" image icon.
* "delete_link_html" for custom look of "delete"-buttons. Defaults to Django's built-in "x" image icon.
**Use example: **
*admin.py:*
class NameInline(admin.TabularInline):
model = Name
extra = 1
class PersonAdmin(admin.ModelAdmin):
inlines = [NameInline]
class Media:
js = ['js/jquery-1.3.2.min.js', 'js/ui/ui.core.js',
'js/ui/ui.sortable.js', 'js/dynamic_inlines_with_sort.js',]
css = { 'all' : ['css/dynamic_inlines_with_sort.css'], }
admin.site.register(Person, PersonAdmin)
*models.py:*
class Person(models.Model):
year_born = models.PositiveIntegerField(_('year born'), null=True, blank=True)
class Name(models.Model):
profile = models.ForeignKey(Profile, verbose_name=_('profile'))
position = models.PositiveIntegerField(_('position'), default=0)
name = models.CharField(_('name'), max_length=100)
class Meta:
ordering = ('position',)
*dynamic_inlines_with_sort.css:*
/* To make row height of saved items same as others */
.inline-group .tabular tr.has_original td { padding-top:0.5em; }
.inline-group .tabular tr.has_original td.original p { display:none; }
Please post bugs in comments.
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.
Automatically create a unique slug for a model.
Note that you *don't* need to do `obj.slug = ...` since this method updates the instance's slug field directly. All you usually need is: `unique_slugify(obj, obj.title)`
A frequent usage pattern is to override the `save` method of a model and call `unique_slugify` before the `super(...).save()` call.
This snippet creates thumbnails on-demand from a ImageField with any size using dynamics methods, like ``get_photo_80x80_url`` or ``get_photo_640x480_filename``, etc.
It assumes you have an `ImageField` in your Model called `photo` and have this in your models.py:
import re
from os import path
from PIL import Image
GET_THUMB_PATTERN = re.compile(r'^get_photo_(\d+)x(\d+)_(url|filename)$')
`models.py` example:
import re
from os import path
from PIL import Image
from django.db import models
GET_THUMB_PATTERN = re.compile(r'^get_photo_(\d+)x(\d+)_(url|filename)$')
class Photo(models.Model):
photo = models.ImageField(upload_to='photos/%Y/%m/%d')
<snippet here>
Example usage:
>>> photo = Photo(photo="/tmp/test.jpg")
>>> photo.save()
>>> photo.get_photo_80x80_url()
u"http://media.example.net/photos/2008/02/26/test_80x80.jpg"
>>> photo.get_photo_80x80_filename()
u"/srv/media/photos/2008/02/26/test_80x80.jpg"
>>> photo.get_photo_64x64_url()
u"http://media.example.net/photos/2008/02/26/test_64x64.jpg"
>>> photo.get_photo_64x64_filename()
u"/srv/media/photos/2008/02/26/test_64x64.jpg"
Modified version of [Profiling Middleware](http://www.djangosnippets.org/snippets/186/)
Prints profile results for method, additionally groups results by files and by modules (for django uses top level modules as groups). Works for Windows.
Usage: append ?prof or &prof= to any URL pointing to django application after adding ProfileMiddleware to middlewares in yours settings.py.
NOTICE: ProfileMiddleware uses hotshot profiler which is not thread safe.
A filter to resize a ImageField on demand, a use case could be:
`
<img src="object.get_image_url" alt="original image">
<img src="object.image|thumbnail" alt="image resized to default 200x200 format">
<img src="object.image|thumbnail:"200x300" alt="image resized to 200x300">
`
The filter is applied to a image field (not the image url get from *get_image_url* method of the model), supposing the image filename is "image.jpg", it checks if there is a file called "image_200x200.jpg" or "image_200x300.jpg" on the second case, if the file isn't there, it resizes the original image, finally it returns the proper url to the resized image.
There is a **TODO**: the filter isn't checking if the original filename is newer than the cached resized image, it should check it and resize the image again in this case.
The `{% switch %}` tag compares a variable against one or more values in
`{% case %}` tags, and outputs the contents of the matching block. An
optional `{% else %}` tag sets off the default output if no matches
could be found:
{% switch result_count %}
{% case 0 %}
There are no search results.
{% case 1 %}
There is one search result.
{% else %}
Jackpot! Your search found {{ result_count }} results.
{% endswitch %}
Each `{% case %}` tag can take multiple values to compare the variable
against:
{% switch username %}
{% case "Jim" "Bob" "Joe" %}
Me old mate {{ username }}! How ya doin?
{% else %}
Hello {{ username }}
{% endswitch %}
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.