Wednesday, March 13, 2019

First Django View

Our first view will be an "index" view. It will not have much on it other than a general welcome to the site.

To create the index page we need to do seven things:

  1. Create the view itself.
  2. Register the url in urls.py
  3. Create a templates directory in techapp
  4. Create a base.html file that will be the basis of all our web pages
  5. create a techapp subdirectory in the templates directory
  6. Create an index.html template
  7. Run the server and see if it works

Creating the View

Open the views.py file in techapp/

The first view is going to be quite simple. Here is the code and then I will explain.

from django.shortcuts import render

# Create your views here.
def index (request):
    return render(request, 'techapp/index.html')

Our view is a function like any python function beginning with "def." (Views can be classes as well, but we will stick the functions for this app.) We give it a name, "index." It takes an argument "request." The request argument contains all the information of the request to the web server. There are several values that can be found in this request, but for now just know that it contains some web page's request for our index page. Our index is doing nothing but returning a web page so we are returning a rendering of the web page. Later we will also return--pass--data from the view to web pages. But here we are just telling the requester where to find the html page for index. It will be in a techapps folder. More on this in a minute.

Registering the View with the urls

Next we register the view in our urls.py file that we created in the techapp folder. Remember the we set the project level urls.py to include this folder and file. So the program will go the the project level urls and then come the app level urls.py. Here is the path for the index.

from django.urls import path
from . import views

urlpatterns=[
    path('', views.index, name='index'),
]

Note that we had to import path from django.urls and also that we need to import our views. The name value provides a shortcut that can be used in urls as we see later. Only the index file can use empty quotes for the initial path statement.

Setting up the templates

Django assumes that your web pages will be kept in a templates folder. You can change this in the settings.py file, but we are going to go with the defaults. It does not create that folder for you, though. So right click on techapp and choose "New Folder." Name the folder "templates." It is important that the name be exact. It must be plural and it must be all lower case. Otherwise, you will get errors that it can't find your web pages.

The base.html file

The base.html file will be the "template" for your templates, if you will. It has the heading and body for all your web templates. Those templates will be inserted into the content area block in the center of the page. Here is a sample base.html file. I have included the bootstrap CSS files to provide some minimal formatting for our we pages.

<!DOCTYPE html>
<html>
    <head>
        <title>Tech Reviews</title>
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
        <link href='//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
        
       
    </head>
    <body>
        <div class='jumbotron' style="background-color: Navy; color: white;">
            <h1>Tech Reviews</h1>
        </div>
        <nav class="navbar navbar-default">
                <div class="container-fluid">
                <div class="navbar-header">
                <a class="navbar-brand" href="{% url 'index' %}">Tech Reviews</a>
                </div>
                <ul class="nav navbar-nav">
                   
               
                </ul>
                </div>
                </nav>
        <p>&nbsp;</p>
        <div class="container">
        {% block content %}
        {% endblock content %}
        </div>
    </body>
</html>

Adding the subfolder techapp to templates

The base.html file should be in the templates directory. All the other templates should be in sub folder inside the templates folder that has the name of the app, so in our case techapp/. Inside this templates/techapp folder we will add our index.html file. Here is a look at our files and directories:

The index.html file

Now we need to create our index.html file. It will not be a complete HTML document. It will not have the DOCTYPE, the html, head, or body tags. They are in the base.html. We will simply write the html that applies to our insert. Here is the html and python.

{% extends 'base.html' %}
{% block content %}
<!--This is a comment-->

<h2>Tech Reviews</h2>
<p>Welcome to the site that
    reviews everything tech
</p>
<p>Under construction</p>

{%  endblock %}

The first line tell the program to "extend" the base.html file. This will provide the overall structure of the web page. The next line of python scripting tells the program that the following area contains the content that will be included in the base.html file's content section. We do a little inconsequential html and then close the content block. Save this file (and any other files you have not saved yet).

Run the server

Lastly, for this part we are going to run the server and test our index page. On the command line in the techreviewproj folder, key in and execute this command.

python manage.py runserver

(on Ubuntu it should be "python3").

If all works your should see this response:

Performing system checks...

System check identified no issues (0 silenced).
March 13, 2019 - 09:24:41
Django version 2.1.1, using settings 'techreviewproj.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

If not, you will see an error list. Correct the errors and save any changes. (The errors are most likely typing errors or errors of case. Everything must match exactly.)

Open your browser and type in the address of http://127.0.0.1:8000/techapp/

You should end up with and index page that looks something like this:

Previous Next

No comments:

Post a Comment