Login

Add a print link to the admin to print individual record

Author:
jimmylam
Posted:
November 14, 2008
Language:
Python
Version:
1.0
Score:
1 (after 3 ratings)

This is a view that can be used to add a print button (link) in the admin change form for an individual record.

Pretty simple to use. A nice enhancement to it is to be able to pull the model field name tie with the field value, something like making {{ object.as_dl }} available to the template.

PS: The code is a modification from the django.views.generic.list_detail.object_detail

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from django.template import loader, RequestContext
from django.http import Http404, HttpResponse, HttpResponseForbidden
from django.core.xheaders import populate_xheaders
from django.core.paginator import Paginator, InvalidPage
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.loading import get_model

def print_detail(request, app_label, model_name, pk, template_name=None, template_name_field=None,
        template_loader=loader, extra_context=None,
        context_processors=None, template_object_name='object',
        mimetype=None):
    """
    Put the following line in your urls.py BEFORE your admin include
    (r'^admin/(?P<app_label>[\d\w]+)/(?P<model_name>[\d\w]+)/(?P<pk>[\d]+)/print/', 'biola.utils.print_view.print_detail'),

    Generic detail of an object.

    Templates: ``<app_label>/<model_name>_print_detail.html``
    Context:
        object
            the object
    """
    if not request.user.is_staff:
        return HttpResponseForbidden()
    if extra_context is None: extra_context = {}
    try:
        model = get_model(app_label, model_name)	
        obj = model.objects.get(pk=pk)
    except ObjectDoesNotExist:
        raise Http404, "No %s found matching the query" % (model._meta.verbose_name)
    if not template_name:
        template_name = "%s/%s_print_detail.html" % (model._meta.app_label, model._meta.object_name.lower())
    if template_name_field:
        template_name_list = [getattr(obj, template_name_field), template_name]
        t = template_loader.select_template(template_name_list)
    else:
        t = template_loader.get_template(template_name)
    c = RequestContext(request, {
        template_object_name: obj,
    }, context_processors)
    for key, value in extra_context.items():
        if callable(value):
            c[key] = value()
        else:
            c[key] = value
    response = HttpResponse(t.render(c), mimetype=mimetype)
    populate_xheaders(request, response, model, getattr(obj, obj._meta.pk.name))
    return response
    """
    Create your own change_form.html for your admin view:
    {% extends "admin/change_form.html" %}
    {% load i18n %}
    
    {% block object-tools %}
    {% if change %}{% if not is_popup %}
      <ul class="object-tools"><li><a href="print/" class="printlink" target="_blank">{% trans "Print" %}</a></li><li><a href="history/" class="historylink">{% trans "History" %}</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 %}
    """

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

ssavelan (on February 18, 2009):

I like the snippet. Just about exactly what I was looking for. Of course I will still have to write my own template but that was pretty-much expected.

I had to: from django.core.xheaders import populate_xheaders from django.http import HttpResponse from django.db.models import get_model from django.core.exceptions import ObjectDoesNotExist from django.template import loader

for my template_dir layout how I thought would be good for me I did:

template_name = "admin/%s/%s_print_detail.html" % (model._meta.app_label, model._meta.object_name.lower())

Nice post though. This is actually my first admin 'customization' and it went pretty smoothly and I learned some stuff, THANKS!

#

asinox (on September 7, 2009):

Very nice, i was looking for this, but i got error:

'str' object is not callable

#

middlelord (on September 20, 2011):

Thanks for the snippet, can someone help me with the error I get?? I am sure it is something I must have not done correctly. I receive error:Exception Value:

admin/projectname/appname_print_detail.html not found... but I am not sure if i was supposed to create it. Thanks for the response The django commmunity is great!

#

Please login first before commenting.