I'm a beginner to web development in django, and I'm wondering why views needed to be rendered with functions and classes? Can't the urls module just link the url to the HTML template directly rather than indirectly through a function-based view?
-
No, you need to call the view in order to do for example some processing or filtering of the data that will be rendered. The views are taking care of the things that happens on the background, like working with the forms or DB models, you cant do this by rendering only the html template.jv95– jv952020-05-24 20:53:30 +00:00Commented May 24, 2020 at 20:53
-
Most views are not simply rendering templates, most of them make queries, process data, render data, update data. In fact most POST requests never render a template at all.willeM_ Van Onsem– willeM_ Van Onsem2020-05-24 20:56:10 +00:00Commented May 24, 2020 at 20:56
-
If you only aim to make a website of static files, you do not need a web framework like Django, then you make a set of HTML pages, and use something like apache to serve these to the browser.willeM_ Van Onsem– willeM_ Van Onsem2020-05-24 21:07:51 +00:00Commented May 24, 2020 at 21:07
2 Answers
You can indeed have the urls module just render the HTML for you right way. For that, you can use direct_to_template: https://django.readthedocs.io/en/1.4.X/topics/generic-views.html#using-generic-views
You would rely on a function when you have any extra processing to be done before sending the response ("rendered template") to the user. You could need to log the user's IP address, for example, or you could load data from a database to fill in the template. Or you can not even have to render a HTML, but a JSON instead. That's why you would need a custom view, which would be implemented in either a function or class.
Comments
So the point of Django in general is you're going to want to be serving more than just static HTML, you'll probably want to process that in some way. As other answers have said, if you just want to return HTML, you can use a TemplateView (https://docs.djangoproject.com/en/3.0/ref/class-based-views/base/#templateview) or just have your web server server the static files (https://docs.djangoproject.com/en/3.0/howto/static-files/deployment/)
Unless your use case is a single page app, its highly likely you'll have some HTML that's common to multiple pages, in which case you can include and extend templates.