[Answered ]-Creating Generic Views in Django

2đź‘Ť

âś…

You’re just a bit confused about Django’s terminology. Almost all views use a template to render the actual markup (HTML, XML, whatever) that is sent back to the browser.

A Django Generic View is just a Class based version of writing your own functional view. So instead of something like:

def show_template_with_data(request):
    template = "myapp/show_data.html"
    return render(request, template, {'data1': 1, 'data2': 2})

you would use Python classes and OO and do:

class ShowTemplateWithData(TemplateView):
    template_name = "myapp/show_data.html"

    def get_context_data(self, **kwargs):
        context = super(ShowTemplateWithData, self).get_context_data(**kwargs)
        context['data1'] = 1
        context['data2'] = 2
        return context 

These two are equivalent one is just using functions and the other Class Based Views.

In Django, views are the code that determines what action is taken, what data is given to the template (for example based on logged in user), etc. a “template” is just the HTML with placeholders/loops/etc that displays it.

But no, you shouldn’t be deleting the template HTML files, both styles of views will need them.

👤Frank Wiles

Leave a comment