Creating website with Python using VS Code on macOS

There are several web frameworks available for creating website with Python. The popular once are Django, Flask, Prymid, TurboGears, Web2py, etc… Here, in this article we will go over the step by step instruction on how to use Python for website development using Django as the web framework, Visual Studio Code as the editor on macOS.

Tools & technologies used

  • Python 3.7.4.
  • Django 2.2.6.
  • Visual Studio Code 1.39.2.
  • macOS Catalina 10.15.

Prerequisites

Creating a Python virtual environment

To start with, you will see how to create a python project with virtual environment for the web application. Django package will be installed in this virtual environment in the next section.

  1. Launch VS Code.
  2. Open a folder for Python django workspace by going to Files >> Open … >> Select or create a folder in the finder window and open it. For this illustration, name the folder as py_django_web. This will be your Python workspace.
  3. In VS Code Editor, open the Command Palette, by pressing Shift, Command and P keys.
  4. Search and start Terminal: Create New Integrated Terminal. The terminal panel will open at the bottom.
  5. In the terminal run the commands.
    • python3 -m venv env
    • source env/bin/activate
  6. A new virtual environment called env is now created for the workspace. To see this, go to the explorer panel and expand the newly created folder under the workspace.
    Creating website with Python
  7. Open the Command Palette again and search and select Python: Select Interpreter. Now you will see the newly created virtual environment (something similar to Python 3.7.4 64-bit (‘env’, venv)). Select the virtual environment as your interpreter.
    Select python virtual environment
  8. Virtual environment is ready.

Creating django project

As the virtual environment is ready, it is time to install the django package in the virtual environment and set a startup web project.

  1. Again start Terminal: Create New Integrated Terminal. from the command palette.
  2. In the integrated terminal run the command:
    • python3 -m pip install django
  3. Django and its dependent packages will be downloaded and installed. This installation may take several minutes to complete. (I had to wait for nearly 20 minutes for this installation to complete on my laptop.)
    installing django and it's dependencies
  4. Virtual environment is ready for Django web development and coding. Now, you have to create a startup web project.
  5. Go back to the virtual environment’s Integrated Terminal and run the below command. (NOTE: Don’t forget to include the dot . at the end of the command which directs the command to the current directory. dj_web is the name of the sub folder the command supposed to create.)
    • django-admin startproject dj_web .
  6. Django web project is now created. You can see the sub folder named dj_web and few files underneath.
    Creating django web project
  7. To check the web project, you have to start the web server. To start the web server run the command:
    • python3 manage.py runserver
      Starting python django web server
  8. The Django web server is now started in the post 8000. (NOTE: If you notice the above image, while starting the server there is a message in red letters saying about unapplied migrations. To apply the migrations and remove this message read my article Django: You have .. unapplied migration(s). You can do this later after properly closing the web server.)
  9. To launch the default home page from your django project just cmd+click the url (http://127.0.0.1:8000/) displayed the result in the terminal or copy it and enter it to your browser. The default home page looks like this:
    default django project home page
  10. If you can see this default page the it is confirmed that django web project is installed properly.
  11. Once done, close the web server. To close the web server go to the terminal and press CONTROL-C.

Creating a web app

Now you have to create a django web app. Follow these steps to create a web app.

  1. In the Visual Studio Code Terminal run this command. In this command dj_app is the name of the web app:
    • python3 manage.py startapp dj_app
  2. The above startup command creates a folder called dj_app. This the the folder which contains all the code files for the django web app.
    Creating web app in django project
  3. Now open the file dj_app/views.py and replace the existing the code with the below code. In this def home(request) and the following line is how you define a view and what to render in the browser. This definition is for home page.
from django.http import HttpResponse

def home(request):
    return HttpResponse("Hi, This is my first django view!")
  1. Create a new file named urls.py under the folder dj_app. This file is used for specifying the url route patterns of the views under the app folder dj_app. Add the below content to dj_app/urls.py.
from django.urls import path
from dj_app import views

urlpatterns = [
    path("", views.home, name="home"),
]
Adding urls.py and it's contents
  1. Now, you have to import this file dj_app/urls.py to the master urls file under dj_web folder. Only then the url route settings we have done in dj_app will be handled by the web project.
  2. To import, open the file dj_web/urls.py and replace the code with the below code:
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path("", include("dj_app.urls")),
]
Modify contents in master urls.py
  1. The web app and the basic view (home) is now ready. Now, start the web server by running the command python3 manage.py runserver and launch the web app using the the url http://127.0.0.1:8000/ in any browser.
Basic website with Python django
  1. Don’t forget to close the web server once done.

Creating launch profile

As you have seen already, every time when you start the python django web server you have to type in a command in the terminal. This will become difficult during the development process. You can overcome this problem by creating a launch profile. Launch profile is part of the the debugger settings in VS Code. As debugging is out of scope of this article In this section, I will go through launch profile setting alone. I will write another article with in depth details on debugging.

  1. Go to VS Code’s debug view by pressing the debug icon at the left activity panel.
  2. Press the settings icon (gear icon) with a warning dot at the top, next to the No Configuration.
Open VS Code Debug view
  1. Pressing the settings icon, a prompt box opens at the top with the list of debugger options. From the list select Django: Launch and debug a Django web application.
Selecting debugger
  1. A new file called launch.json will be created under the .vscode folder and opens in the editor window. This file will have the debug configurations. Make sure the content of the file is similar to the screenshot below. Here the values in the program and the args section performs similar to the terminal command python3 manage.py runserver –noreload.
  2. Save the file.
Newly created launch.json file
  1. Now, check the debug configuration drop down list at the top left. Python: Django will be selected by default. If not choose it manually.
Debug configuration drop down
  1. The launch profile setting is now complete. You can now start the web server and the debugger just by pressing the green arrow found in between DEBUG and Python: Django. Other ways to start the web server in debug mode is by pressing F5 key or by going to the menu >> Debug >> Start Debugging.
Launching web server and the debugger
  1. The web server is now started in debug mode. You can identify the changes happened in the Visual Studio Code editor. A debugging toolbar appears at the top and the color of the status bar changes to orange.
Launching web server in debug mode
  1. To open the web app in the browser either command+click the url http://127.0.0.1:8000/ or copy and paste it to the browser.
  2. NOTE: If you want to start the web server without debug mode, then press the Control + F5 keys.
  3. Once done, don’t forget to close the web server by pressing CONTROL-C.

Using templates

The web app view (home) you have created earlier has only plain text. It is possible to add HTML in the Python code within the view definition function in views.py. But, I would strongly advise not to mix HTML code with python code. Avoiding HTML in python code will improve the security of your application from cross site scripting attack. It will also increase the code readability. In Django, you can use templates to segregate HTML code from python code.

In this section, you will see how to create a template for HTML and add placeholders to capture and render the data sent from the python code during run-time.

  1. Open the file dj_web/settings.py.
  2. Find the list called INSTALLED_APPS and add dj_app to it:
    • 'dj_app',
      Add web app to the INSTALLED_APPS list
  3. In the dj_app folder create a sub-folder called templates.
  4. Now, create another sub-folder called dj_app under templates folder. The name of the folder should be the same as the name of the web app.
    Create sub-folders under web app
  5. Under the /dj_app/templates/dj_app folder create a file called hello.html.
  6. Add the below content to the hello.html file. In this, the place holders are marked by double opening and double closing curly braces {{ and }}. Here there a three placeholders, one for name variable and two for date variable with filter |.
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>Hello, This is my first template.</title>
</head>

<body>
    <strong>Hi {{ name }}</strong>, <br>
    Current date is {{ date | date:"l, d F Y" }}. <br>
    Current time is {{ date | time:"h:i:s A" }}.
</body>

</html>
Content of hello.html template file
  1. Open the views.py file add these import statements along with the existing one.
from datetime import datetime
from django.shortcuts import render
  1. In the same file (views.py), add this function to load the template we have just created.
def hello(request, name):
    return render(
        request,
        'dj_app/hello.html',
        {
            'name': name,
            'date': datetime.now()
        }
    )
  1. After the changes, the content of the views.py file looks like this:
Content in views.py file after adding hello view
  1. Now go to dj_app/urls.py file and add a route entry under urlpatterns list for our new view.
path("hello/<name>", views.hello, name="hello"),
Adding hello view's route ot urls.py file
  1. The hello view with the HTML template is now created and the URL route is set.
  2. Start the web server without debug mode by pressing the Control + F5 keys.
  3. In the browser, launch the web app and navigate to /hello/name url. Let name be some name.
Brousing view with template

Creating & using static files in web app

Now you will see how to add and serve static files like .css or .js files to your Django web app.

Setup the web app to use static files

  1. Open dj_web/urls.py file and add this import statement.
    • from django.contrib.staticfiles.urls import staticfiles_urlpatterns
  2. Add this line to the end of the same file.
    • urlpatterns += staticfiles_urlpatterns()
Setup the web app to use static files

Create a static file

  1. Under the dj_app folder create a sub-folder called static.
  2. Again create a sub-folder called dj_app under static. The sub-folder name should be the same as the name of the web app.
  3. in the /dj_app/static/dj_app folder add style sheet file called site.css and add this content.
body {
    background-color: powderblue;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
}

h1 {
    font-family: Arial, Helvetica, sans-serif;
    font-weight: bold;
    color: blue;
}
Creating static file

Refer static file in template

  1. Open the template file you have created before (templates/dj_app/hello.html)
  2. Add this code just below the title tag at the head section. The tag {% load static %} allows the template to use {% static %} tag for referring a static file.
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'dj_app/site.css' %}" />
  1. Add or modify the content in the tag and add a H1 tag. this is to test and make sure the static file style.css is served by the Django web server. Here is my template file after changes:
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>Hello, This is my first template.</title>
    {% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'dj_app/site.css' %}" />
</head>

<body>
    <h1>Hi {{ name }},</h1>
    Current date is {{ date | date:"l, d F Y" }}. <br>
    Current time is {{ date | time:"h:i:s A" }}.
</body>

</html>
Refer static file in template
  1. Now, run the web app in non-debug mode and browse the url hello/name again and see if the styles are rendering properly. Here is the result.
Running django web app along with a static file

Adding images and other media files is same as adding other static files. Sometime you may need to segregate images in a separate folder. If you still need the steps to add images to web app, then follow the article Adding image to Python Django web app.

Now you know how to add and serve a static file like style sheet, java script, fonts, images, etc…

Creating and using a base template

In most of the web applications there will be multiple pages. Some of the content in all the pages will be common for all the pages. For example the navigation menu will be common to all the pages. So, it is always a good practice to have these type of common content in a single file. It is also easy to maintain.

In Django web app, the base template file will have the common content pertinent to several templates and views. Let us see how and where to crate a base template and refer it to other templates or views.

  1. Create a file called layout.html in the folder templates/dj_app. This will be your base template.
  2. Add these content to the layout.html file. Here, the tag {% load static %} and the following link tag are used to load the static content. The {% url %} tag is used to generate the url of other pages or views in run time. The section starting from {% block content %} and ending with {% endblock %} tag is used by the other templates to override and fill with the content.
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>{% block title %}{% endblock %}</title>
    {% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'dj_app/site.css' %}" />
</head>

<body>
    <div class="navbar">
        <a href="{% url 'home' %}" class="navbar-brand">Home</a>
        <a href="{% url 'products' %}" class="navbar-item">Products</a>
    </div>

    <div class="body-content">
        {% block content %}
        {% endblock %}
    </div>
    
    <div class="footer-content">
        <hr />
        <footer>
            <p>Copyright © 2019 Django Web Project</p>
        </footer>
    </div>
</body>

</html>
Creating base template
  1. Now, open the style sheet file site.css in the folder static/dj_app and replace the existing content with this:
body {
    font-family: Verdana, Geneva, Tahoma, sans-serif;
}

h1 {
    font-family: Arial, Helvetica, sans-serif;
    color: darkgray;
}

.navbar {
    background-color: lightgray;
    font-size: 11px;
    font-family: Arial, Helvetica, sans-serif;
    color: black;
    padding: 8px 5px 8px 5px;
}

.navbar a {
    text-decoration: none;
    color: inherit;
}

.navbar-brand {
    font-size: 1.2em;
    font-weight: 600;
}

.navbar-item {
    font-variant: small-caps;
    margin-left: 30px;
}

.body-content {
    padding: 5px;
}

.footer-content{
    font-size: small;
    font-style: italic;
}
  1. Go to the folder templates/dj_app and add a template file for home view. Let’s call it home.html and add the content below. The first line refers the base-template layout.html to this template. Within the title block and content block you can add some title and content of the page.
{% extends "dj_app/layout.html" %}
{% block title %}

{% endblock %}
{% block content %}

{% endblock %}

After adding title and content, the home.html looks like this:

{% extends "dj_app/layout.html" %}
{% block title %}
Home Page | My Tec Bits
{% endblock %}
{% block content %}
<h1>Hi There,</h1>
<p>This is your home page.</p>
{% endblock %}
Hamo layout using base template
  1. Open views.py and replace the home view function with the below code:
def home(request):
    return render(request, "dj_app/home.html")
home function in views.py
  1. In the web app’s (dj_app) urls.py file make sure the url route for the home page is available. If not, add it:
path("", views.home, name="home"),
url route for home view in app's urls.py
  1. Home page is now ready. Now, you have to create another template for the the products page.
  2. Go to the folder templates/dj_app again and add a template file for products page. Let’s call it products.html and add the content given below below. (NOTE: While creating several html templates, It will be a good practice to create a code snippet and use it instead of copy paste the template code in several files. Read the article Creating code snippet for Python Django web app in VS Code.)
{% extends "dj_app/layout.html" %}
{% block title %}
Products Page | My Tec Bits
{% endblock %}
{% block content %}
<h1>Products</h1>
<p>This page will have the list of all products.</p>
{% endblock %}
Products template using base template
  1. Open views.py and add the properties view function with the below code:
def products(request):
    return render(request, "dj_app/products.html")
properties function in views.py
  1. In the web app’s urls.py file add the url route for the properties page.
path("products/", views.products, name="products"),
url route for products page in app's urls.py
  1. Now, run the project and open the home page in browser. Here is a simple website with Python Django using base template and multiple page templates.
website with Python rendered using base template

With this, I’m completing this article, In the coming days, I will write about using database, debugging and creating code snippets.

Next Steps

Reference

  • I have referred visual studio tutorial and created this article in macOS perspective and in a simplified manner.

Related Articles & Tools

Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.