[Django]-Using two templates from one view

5👍

You can use a parameter in your url and implement a view like

def myview(request) :

    type = request.GET.get('type', 'html')

    # do processing
    if type == 'html':
        # return html
    else if type == 'csv':
        # return csv

If you access a url like http://yourserver/myview?type=csv it will render the csv part of the view. When the url http://yourserver/myview is accessed it will return the html part of the view.

👤Rohan

1👍

Rohan’s answer is absolutely the right paradigm. For an excellent tutorial-style introduction to this topic, cf. Multiple Templates in Django.

Here are a few quotes (all credit goes to Scott Newman).

To serve a printable version of an article, for example, we can add ?printable to the end of the URL.

To make it work, we’ll add an extra step in our view to check the URL for this variable. If it exists, we’ll load up a printer-friendly template file. If it doesn’t exist, we’ll load the normal template file.

def detail(request, pid):
    '''
    Accepts a press release ID and returns the detail page
    '''
    p = get_object_or_404(PressRelease, id=pid)
    
    if request.GET.has_key('printable'):
        template_file = 'press/detail_printable.html'
    else:
        template_file = 'press/detail.html'

    t = loader.get_template(template_file)
    c = Context({'press': p})
    return HttpResponse(t.render(c))

He continues with template overrides and different templates by domain names. All this is excellent.

Leave a comment