If you have arrived to this web page, you must be knowing how urls are mapped to web pages in Django. These web pages are created using templates for reusability purposes. So a full fledged content of views.py would be somewhat like -
from django.template import Context, Template
from django.template import HttpResponse
t = Template(“<template_content>”)
c = Context(<dictionary_having_mapping_from_variables_to_values>)
t.render(c) # this brings the actual required output
html = t.render(c)
return HttpResponse(html)
How to reduce the overhead of writing whole of template in views.py file? You can call template from a separate file. To achieve this, you need to change TEMPLATE_DIRS in settings.py to include the directory path where you want to place the template file. Now the above code can be rewritten as -
from django.template import Context
from django.template.loader import get_template
from django.template import HttpResponse
t = get_template(‘abc.html’)
c = Context(<dictionary_having_mapping_from_variables_to_values>)
t.render(c) # this brings the actual required output
html = t.render(c)
return HttpResponse(html)
where abc.html contains your template content and lies in the directory path you mentioned in TEMPLATE_DIRS variable.
Although above trick didn’t make views.py concise, but it did provide a separation of template code(frontend) from views(backend), which now can be modified separately without affecting each other. Now, comes the actual trick to make views.py concise. There is a function called render_to_response() in django.shortcuts module, which performs the following tasks in one go -
t = get_template(‘abc.html’)
c = Context(<dictionary_having_mapping_from_variables_to_values>)
t.render(c) # this brings the actual required output
html = t.render(c)
return HttpResponse(html)
All the above tasks can be achieved through one statement -
return render_to_response(‘abc.html’,<dictionary_having_mapping_from_variables_to_values>)
Now, if you say that you don’t even want to mention that dictionary mapping, there is a way out, use locals() -
return render_to_response(‘abc.html’,locals())
Using locals automatically picks up variables and their values from the view. So obviously for this thing to work, variable names in template and views should match.
Related posts:
