Function-Based Views (FBV) in Django 


               


Function-Based Views (FBV) in Django



Python


In this article, we go over what function-based views are in Django.

Function-based views are views in Django that are defined by functions.

Using functions, we can create views using certain functions in Django such as HttpResponse() (to hardcode HTML into a view) or render() to render a template file into a view.

We'll show this below.

So, let's say that we've created an app, called Blog, and that we've already installed the app in the settings.py file and we've already specified the path to the app in the urls.py file.

Let's now go to the views.py file in the app, Blog.


views.py File

So let's define a few functions in our views.py file, so that you can see directly what function-based views are.



So, in this views.py file, we have created 3 functions, view1, view2, and view3.

In each function, we return an HttpResponse, displaying View 1, View 2, or View 3, for view1, view2, and view3 functions.

So, in total, we have 3 functions.

Now, let's go to the urls.py file in the App directory and see how we can show these function-based views.


urls.py File

So, now we go to the urls.py file in the App directory.



We can also rewrite this file, so that the second parameter to url data type is the function alone.

This is how it would look like rewritten.



This is just another way of rewriting the urls.py file so that only the function name is included as the second parameter of

Now, in the urls.py file, we specify the url that a user would have to type or the url that a user would be redirected if clicking a link.

So, basically whatever path we specified in the urls.py file in the root directory would be continued in this urls.py file in the app.

So, if in the urls.py file in the root directory, we specified the following:



This means that if we type in, http://127.0.0.1:8000/Blog/view1, we would be redirected to view 1.

This means that if we type in, http://127.0.0.1:8000/Blog/view2, we would be redirected to view 2.

This means that if we type in, http://127.0.0.1:8000/Blog/view3, we would be redirected to view 3.

So, this is how function-based views work in Django.

We can create as many functions as we want in the views.py file and then we can put these functions in the urls.py file so that we can render whatever we created, based on the url a user goes to.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...