According to Django documentation A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image . . . or anything, really. The view itself contains whatever arbitrary logic is necessary to return that response. This code can live anywhere you want, as long as it’s on your Python path. There’s no other requirement–no “magic, ” so to speak. For the sake of putting the code somewhere, the convention is to put views in a file called views.py, placed in your project or application directory.
A Django project/ consists of a main folder also know as Django folder which consists of
settings.py and one or more app folders which contains
As shown in image, geeks_site is project folder, brand is an app, db.sqlite3 is default database provided for django and manage.py is python file which runs command to manage changes in project.
python manage.py runserver python manage.py startapp python manage.py migrate python manage.py makemigrations
Type of Views
There are two type of views in Django.
- Function based views
- Class based views
In this articles, we will talk about function based views.
Defining and using views –
Every app in Django project by deafult contains a python file named views.py. Using views.py, we control what to display user on webpage.
Now, open brand/views.py and write following lines into it…
Any function in views.py takes requestparameter by default.
To connect functions defined in views.py, you need to do URL mapping.
geeks_site/urls.py and import ViewDemo function from brand/views.py.
from brand.views import ViewDemo
In urlpatterns, add a line
Now, your geeks_site/urls.py is now,
Now, URL mapping is done. Goto your terminal and start server by using the following commands:
python manage.py runserver
Goto URL http://127.0.0.1:8000/hello-world/ and you will see
- Createview - Class Based Views Django
- Render a HTML Template as Response - Django Views
- Create View - Function based Views Django
- Update View - Function based Views Django
- List View - Function based Views Django
- Detail View - Function based Views Django
- Delete View - Function based Views Django
- Django CRUD (Create, Retrieve, Update, Delete) Function Based Views
- Python | Django News App
- Django Migrations | Python
- Weather app using Django | Python
- Django URL patterns | Python
- Python | Django Admin Interface
- Python | Form validation using django
- Intermediate fields in Django | Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : Akanksha_Rai