django admin preview
posted on june 12th in django
Picked up a quick tip over LLR for quick django admin previews. This works perfect on my projects.
Add a new preview view to your app
# views.py
from django.contrib.admin.views.decorators import staff_member_required
from django.views.generic.list_detail import object_detail
@staff_member_required
def preview(request, object_id):
return object_detail(request, object_id=object_id, queryset=Article.objects.all(),
template_object_name = 'article', )
We now just add a new URL to call the view
# urls.py
(r'^admin/-appname-/article/(?P<object_id>[0-9]+)/preview/$',
'apps.-appname-.views.preview'),
Now edit the admin change_form template to add a preview button
# templates/admin/-appname-/article/change_form.html
{% extends "admin/change_form.html" %} {% load i18n %}
{% block object-tools %}
{% if change %}{% if not is_popup %}
<ul class="object-tools">
<li><a href="history/" class="historylink">
{% trans "History" %}</a></li>
<li><a href="preview/" class="viewsitelink" target="_blank">
{% trans "View preview" %}</a></li>
{% if has_absolute_url %}<li>
<a href="../../../r/{{ content_type_id }}/{{ object_id }}/" class="viewsitelink">
{% trans "View on site" %}</a></li>{% endif%}
</ul>
{% endif %}{% endif %}
{% endblock %}
Done and done. Obviously the file has to be saved before you can actually preview it. I have an 'active' or 'published' boolean field on my model that I keep unchecked until its been previewed.
References:
http://latherrinserepeat.org/2008/7/28/stupid-simple-django-admin-previews/