This is an inclusion tag that can be used to pull in posts from any feed to a template. It doesn't do any caching, so it may slow down page load times.
Depends on [Feedparser](http://www.feedparser.org).
Template usage:
{% pull_feed 'http://www.djangosnippets.org/feeds/latest/' 3 %}
This is an improvement of snippet 253 in that it supports database queries.
Implementing autocompletion for foreign keys takes a few steps:
1) Put the snippet above into <app>/widgets/autocomplete.py.
2) Create a view of your foreign key model (here: Donator) in <app>/donator/views.py:
from models import Donator
from widgets.autocomplete import autocomplete_response
def autocomplete(request):
return autocomplete_response(
request.REQUEST['text'], Donator, (
'line_1', 'line_2', 'line_3', 'line_4',
'line_5', 'line_6', 'line_7', 'line_8',
'^zip_code', 'location'
)
)
This view returns the autocompletion result by searching the fields in the tuple. Each word from the form field must appear at least in one database field.
3) Create a URLconf that points to this new view.
4) In the form where you need the autocompletion, define the widget of the foreign key field as an instance of AutoCompleteField:
from widget.autocomplete import AutoCompleteField
field.widget = AutoCompleteField(
url='/donator/autocomplete/'),
options={'minChars': 3}
)
The url parameter is the URL connected to the view in step 3), the options dict is passed on to the Ajax.Autocompleter JavaScript object.
Links:
* [Snippet 253](http://www.djangosnippets.org/snippets/253/)
* [Django and scriptaculous integration](http://wiki.script.aculo.us/scriptaculous/show/IntegrationWithDjango)
* [Ajax.Autocompleter](http://wiki.script.aculo.us/scriptaculous/show/Ajax.Autocompleter)
QLeftOuterJoin object allows you to create 'LEFT OUTER JOIN' sql query. It is very usefull if you have to define ForeignKey to 'null=True' (select_related will not work with null=True).
You are allowed to use QLeftOuterJoin like Q object.
Example:
`QLeftOuterJoin('thread_last_post', Post, 'pk', Thread, 'last_post')`
It will generates SQL like:
LEFT OUTER JOIN appname_post AS thread_last_post ON thread_last_post.id = appname_thread.last_post_id
Table could be model or string.
*NOTE Stephen updated his original snippet http://www.djangosnippets.org/snippets/85/ to work with WebFaction, please use his version now*
This code is 95% from Stephen Zabel's snippet at http://www.djangosnippets.org/snippets/85/. However, his snippet, as it was, wouldn't work when enabling SSL for the admin site on Webfaction. For some reason, the default request.is_secure() doesn't behave properly with Webfaction's setup and redirects.
One thing Webfaction does do is add X-Forwarded-ssl='on' to any https requests. So instead of using request.is_secure(), I've just used that.
To setup the admin site with SSL on Webfaction, do the following:
1. Install this middleware wherever you like, and add it to settings.py
2. In your Webfaction panel, create your 'django' application ("application" in the Webfaction sense, not the Django sense)
3. Create two sites. The first, your main site (which I'll call example.com), should use the application 'django' mounted at '/'. Do *not* have HTTPS enabled on this site.
4. For the second site, also use the application 'django', and again mount it to '/', but this time enable HTTPS.
5. In your urls.py, modify the admin URL as follows: `(r'^admin/', include('django.contrib.admin.urls'), {'SSL':True} )`
That should be it! The admin section of the site now requires SSL (as specified in urls.py), and if anyone tries to access the admin via regular http, a redirect to https will occur.
Wizard class - subclass this, supply a done() method and then you can use `MyWizard( [list, of, newforms, classes])` as a view function.
see [#3218](http://code.djangoproject.com/ticket/3218)
Originally posted by [akaihola](http://www.djangosnippets.org/users/akaihola/) as [snippet #169](http://www.djangosnippets.org/snippets/169/). I just redid it as a filter.
This is a very simple way to display images within the admin list view. It is not efficient in the sense that the images are being downloaded in original format, however for cases where the images are not regularly accessed it may be a straightforward option.
Can also be tied into WYSIWYG editors like TinyMCE by adding an appropriate href link in the return value.
Add a value to the context (inside of this block) for easy access.
Provides a way to stay DRYer in your templates.
**NOTE:** This tag is now in Django core, so if you have Django >0.96 (or SVN) then you do NOT need this.
*I suppose I'm kind of stubborn, but I prefer to use underscores to replace spaces and other characters. Of course, that shouldn't hold you back from using the build-in slugify filter :)*
** Forcing the slug to use ASCII equivalents: **
Transforming titles like "Äës" to slugs like "aes" was kind of a trial and error job. It now works for me. I hope `_string_to_slug(s):` proves a rather stable solution. Yet the worst-case scenario is that such characters are lost, I guess that is acceptable.
Other ways of dealing with this problem can be found at [Latin1 to ASCII at Activestate](http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/251871) or in the comments below.
**How to use:**
The slug fields in your model must have prepopulate_from set, the fields specified in it are used to build the slug.
To prevent duplicates, a number is added to the slug if the slug already exists for the current field in another, previous, object. I guess there should be a cleaner way to distinguish between creating a new db entry or updating an existing one, sadly, the db back-end is kind of a black-box to me. At least this works ;)
I choose not to alter the slug on an update to keep urls more bookmarkable. You could even extend this further by only updating the slug field if it hasn't been assigned a value.
If you have a model that has an "ordering" column, and you want to be able to re-position records (eg, order items by priority), this base class should make it fairly easy. To use it, you extend your model using this abstract class, then hook up the pre_save event to the pre_save event of the base class, and you're good to go. Whenever you save an item, it ensures that it has a valid "order" number. The meat of this class is the "move()" method. Just call instance.move(number) where instance is your model instance, and this class will do all the logic necessary to shift around the order numbers for you.
This allows you to create an alphabetical filter for a list of objects; e.g. `Browse by title: A-G H-N O-Z`. See [this entry](http://developer.yahoo.com/ypatterns/pattern.php?pattern=alphafilterlinks) in Yahoo's design pattern library for more info.
NamePaginator works like Django's Paginator. You pass in a list of objects and how many you want per letter range ("page"). Then, it will dynamically generate the "pages" so that there are approximately `per_page` objects per page.
By dynamically generating the letter ranges, you avoid having too many objects in some letter ranges and too few in some. If your list is heavy on one end of the letter range, there will be more pages for that range.
It splits the pages on letter boundaries, so not all the pages will have exactly `per_page` objects. However, it will decide to overflow or underflow depending on which is closer to `per_page`.
**NamePaginator Arguments**:
`object_list`: A list, dictionary, QuerySet, or something similar.
`on`: If you specified a QuerySet, this is the field it will paginate on. In the example below, we're paginating a list of Contact objects, but the `Contact.email` string is what will be used in filtering.
`per_page`: How many items you want per page.
**Examples:**
>>> paginator = NamePaginator(Contacts.objects.all(), \
... on="email", per_page=10)
>>> paginator.num_pages
4
>>> paginator.pages
[A, B-R, S-T, U-Z]
>>> paginator.count
36
>>> page = paginator.page(2)
>>> page
'B-R'
>>> page.start_letter
'B'
>>> page.end_letter
'R'
>>> page.number
2
>>> page.count
8
In your view, you have something like:
contact_list = Contacts.objects.all()
paginator = NamePaginator(contact_list, \
on="first_name", per_page=25)
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
try:
page = paginator.page(page)
except (InvalidPage):
page = paginator.page(paginator.num_pages)
return render_to_response('list.html', {"page": page})
In your template, have something like:
{% for object in page.object_list %}
...
{% endfor %}
<div class="pagination">
Browse by title:
{% for p in page.paginator.pages %}
{% if p == page %}
<span class="selected">{{ page }}</span>
{% else %}
<a href="?page={{ page.number }}">
{{ page }}
</a>
{% endif %}
{% endfor %}
</div>
It currently only supports paginating on alphabets (not alphanumeric) and will throw an exception if any of the strings it is paginating on are blank. You can fix either of those shortcomings pretty easily, though.
This is a field that allows multiple markup types but also stores the pre-rendered result in the database which offers an advantage over calling one of the render methods each time. Example usage looks like:
class BlogPost(models.Model):
...
post = MarkupField()
the various extra fields can then be accessed as follows:
BlogPost.objects.get(pk=1).post # raw content
BlogPost.objects.get(pk=1).post_markup_type # markup type (plain text, html, markdown, rest, textile)
BlogPost.objects.get(pk=1).post_rendered # content of post rendered to html
BlogPost.objects.get(pk=1).post_as_html # property that access post_rendered but marked safe for easy use in templates
After writing my initial version of this I was pointed at the similar http://www.djangosnippets.org/snippets/1169/
I find mine a bit more useful as it includes ReST and includes a mark_safe call to allow showing the rendered HTML directly. I have however borrowed the nice idea of dynamically building MARKUP_TYPES from #1169.
Also available via http://gist.github.com/67724.
"Make fixture" command. Highly useful for making test fixtures.
Use it to pick only few items from your data to serialize, restricted by primary keys.
By default command also serializes foreign keys and m2m relations.
You can turn off related items serialization with `--skip-related` option.
How to use:
python manage.py makefixture
will display what models are installed
python manage.py makefixture User[:3]
or
python manage.py makefixture auth.User[:3]
or
python manage.py makefixture django.contrib.auth.User[:3]
will serialize users with ids 1 and 2, with assigned groups, permissions and content types.
python manage.py makefixture YourModel[3] YourModel[6:10]
will serialize YourModel with key 3 and keys 6 to 9 inclusively.
Of course, you can serialize whole tables, and also different tables at once, and use options of dumpdata:
python manage.py makefixture --format=xml --indent=4 YourModel[3] AnotherModel auth.User[:5] auth.Group
`backupdb` command allows to make a database backup automatically. It's supposed to do this just before a `syncdb`, `reset` or `flush` command in a server deployment. A usual upgrade task in production server could be:
./manage.py backupdb
./manage.py reset myapp
./manage.py syncdb
Put this code in your project's `management/commands/backupdb.py` file.
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.