So far, we have worked on setting up our models and saved some instances of it in the database. So, we have mostly paid attention to the backend of our application.
Now, lets turn our attention to the frontend of our application!
First, let us make a basic page that we want to show as our homepage. To do that, let us first make a folder named 'templates' in our tutorial/students/ directory. Inside that directory, make a blank html page named 'welcome.html'. So, our folder structure should look like:
tutorial |-- assets/ |-- manage.py |-- students | |-- admin.py | |-- apps.py | |-- forms.py | |-- __init__.py | |-- migrations/ | |-- models.py | |-- templates | | `-- welcome.html | |-- tests.py | `-- views.py `-- tutorial/
Now, in the welcome.html file, write out a skeleton of html5 page. Something like:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Hi</title> </head> <body> Welcome!!! </body> </html>
Now, that we have our basic webpage, we would like our application to serve it. The way a django application works is by defining views and then rendering those views when requested. So, we will also define a view and then tell it to render this skeleton of a page that we just created.
To define a view, we must go to our students/views.py file. In this file, we will define our most basic view:
from django.views.generic import TemplateView class WelcomeView(TemplateView): """ This is our welcome screen. Utilizes a template view. """ template_name = 'welcome.html'
As we will be serving web pages primarily, we want to define the urls that we will be serving our pages in. In the default setup that django framework provides us, which can be found in the tutorial/urls.py file, you will see that only one url is defined:
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), ]
urlpatterns is the place where we define all our urls that will be served in the project. Since we don't have any other url defined in the project, we see the default welcome page when we go to 127.0.0.1:8000. When we point our browser to 127.0.0.1:8000/admin/ we see the admin module which is what is defined in the urls.py file.
Lets see what we need to do to change that. Let us define a new urlpattern that points to the root path:
from django.contrib import admin from django.urls import path, include from students import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.WelcomeView.as_view(), name='welcome'), ]
Now, making sure that our server is running, cross your fingers go to 127.0.0.1:8000/ in your favourite browser. If this is the page you see:
Then you are doing amazing!!!
Let us now look at how to display the data that we have in the database next...