Optimised Django App Setup in Windows VSCode 🚀🐍🛠️
Tags: python, django, docker, beginners
Published: 2023-03-28 17:09:38

Setting up a new Django project is a multi-step process that involves installing various tools and packages, creating directories, and configuring settings. This process can take up valuable time and effort that could be better spent on developing your app's functionality.

To help streamline the process and make it easier to start my own Django projects, I created a step-by-step guide that combines essential tools and best practices like VSCode, venv, and .gitignore. This step-by-step is something I created for myself to make setting up Django projects easier and faster. As I found it helpful, I thought it might be beneficial to share it with other developers learning Django. 

In this tutorial, I'll guide you through my process of setting up a new Django web app quickly and efficiently. We'll cover everything from installing Python and Django to creating a virtual environment and generating a requirements.txt file. By the end of this tutorial, you'll have a fully functioning Django app up and running! 🚀🐍🛠️


We're going to build a basic [Django](https://www.djangoproject.com/) app that interacts with the Internet Archive's [Wayback Machine](https://archive.org/web/) API. While intentionally simple, this app demonstrates the use of various technologies and best practices, making it a perfect example for our easy to follow Django app template.

Our app will allow users to input a URL and an optional timestamp, and then check if the Wayback Machine has a snapshot of that URL available. If a snapshot exists, the app will display the archived content; if not, it will inform the user that the URL isn't available in the Wayback Machine.

Here's a quick overview of the app's functionality:

1) We define a `check_wayback_availability()` function that takes a URL and an optional timestamp as arguments. It sends a GET request to the Wayback Machine API and returns the JSON data.

2) The `index` view function handles both GET and POST requests. If it receives a POST request, it retrieves the URL and timestamp from the request, checks the Wayback Machine for a snapshot, and renders the appropriate template based on the availability of the URL.

Although the app itself is fairly simple, it showcases how our Django app template can be used to set up a project quickly and efficiently. By following this tutorial, you'll learn how to implement this app while building a time-saving optimised template that you can use in future projects.

First off, let's build a basic Django environment - 

Step 1: Install Python 3 and Django

Make sure you have Python 3 and Django installed on your system. You can download Python from the [official website](https://www.python.org/downloads/) and install Django using pip:

    pip install django


Step 2: Install VSCode

If you haven't already, download and install [Visual Studio Code](https://code.visualstudio.com/)

Step 3: Open VSCode and launch the terminal

Open VSCode and press Ctrl+~ or click on 'Terminal' in the top menu, then select 'New Terminal' to open the integrated terminal.

Step 4: Create a new directory for your project

Create a new directory for your project using the following commands, I've called mine 'wayback' but you can call yours whatever you like!

    mkdir wayback
    cd wayback


Step 5: Create a virtual environment

    python -m venv venv


This will create a virtual environment named "venv" in your project directory.

Step 6: Activate the virtual environment

    .\venv\Scripts\Activate


Your terminal should now show the virtual environment's name in the prompt.

Step 7: Install Django in the virtual environment

    pip install django


Step 8: Start a new Django project

    django-admin startproject wayback_project .


This will create a new Django project in your current directory.

Step 9: Create a new Django app

    python manage.py startapp wayback_app


Step 10: Run the development server

Run the development server using the following command:

    python manage.py runserver

You should see a message saying that the development server is running at http://127.0.0.1:8000/.

Open a browser and visit http://127.0.0.1:8000/ to see your new Django web app running. It should look something like this - 

![Django template page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fp6bnjupom7ef1iw8nr0.PNG)

You now have a Django web app running in a virtual environment using Python 3 in the VSCode terminal on Windows!

Ok, we've successfully set up a basic Django environment and created a new project and app. Now, it's time to set up `urls.py` in your Django project so that your app's URLs can be included in your project's URLs. In a Django project, you can create multiple apps, each with its own URLs. However, to make these app URLs accessible within the project, you need to include them in the project's main URLs. This enables users to navigate through the app's URLs within the project's URL structure.

In your Django project, open the your_project_name/urls.py file, where your_project_name is the name of your Django project, for this example, mine is 'wayback_project'. Import the include function by modifying the existing import statement at the top of the file:

```python
from django.urls import path, include
```

In the urlpatterns list, add a new entry that includes the URLs from your app:

```python
path('wayback_app/', include('wayback_app.urls')),
```

Now, you need to create a urls.py file inside your app's directory. In the VSCode terminal, run:

    type nul > wayback_app\urls.py


This command will create an empty urls.py file inside your app's directory.

Open the newly created urls.py file in your app's directory, and add the following content:

```python
from django.urls import path
from . import views

urlpatterns = [
# Add your app's URL patterns here
]
```

This file is where you will define the URL patterns specific to your app.

Now your Django project is set up to include URLs from your app. As you create new views in your app, you can add corresponding URL patterns to the urls.py file in your app's directory. Make sure to update the urlpatterns list in the wayback_app/urls.py file with the new paths.

After you have installed all the necessary packages for your Django project, you can use the pip freeze command to generate a requirements.txt file containing a list of all the installed packages and their versions.

To generate the requirements.txt file, navigate to your project directory in the VSCode terminal and run the following command:

    

```
pip freeze > requirements.txt
```


This will create a requirements.txt file in your project directory containing a list of all the installed packages and their versions.

You can then use this file to install the same packages and their versions in a different environment by running the following command:

    pip install -r requirements.txt


This will install all the packages listed in the requirements.txt file in the current environment.

A requirements.txt file ensures all required packages are installed, making it easier to reproduce the same environment in different places. This is crucial for Docker, which requires consistent environments to prevent issues and inconsistencies when running an app in a containerised environment.

To add a `.gitignore` file to your Django project, follow these steps:

In the VSCode terminal, navigate to the root of your project directory if you are not already there.

Create a new .gitignore file:

    type nul > .gitignore


This command will create an empty .gitignore file in your project directory.

Open the .gitignore file in VSCode by clicking on it in the file explorer or using the File > Open menu.

Add the following content to the .gitignore file to exclude common files and directories that should not be tracked by Git:

    # Python artifacts
    __pycache__/
    *.pyc
    *.pyo
    *.pyd
    .Python
    env/
    venv/
    ENV/

    # Django artifacts
    *.log
    *.pot
    *.pyc
    db.sqlite3
    media/

    # VSCode artifacts
    .vscode/

    # Git artifacts
    .git/

Save the file by pressing Ctrl+S or clicking File > Save.

You now have a .gitignore file in your Django project that excludes common files and directories from being tracked by Git. You can customize the file to include or exclude any additional files or directories specific to your project.

Now that you have a basic Django app up and running, let's add some basic HTML and CSS to our web app. This will help to make our app more visually appealing and user-friendly.

Create two folders in your wayback_app folder named 'static' and 'templates'.

Inside the 'static' folder, create a new file named 'styles.css'. Open it and paste the following code:

```css
body {
    font-family: Arial, sans-serif;
}

.welcome {
    color: darkblue;
}
```

Inside the 'templates' folder, create a new file named 'index.html'. Add the following code:

```html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Wayback App</title>
    <link rel="stylesheet" href="{% static 'wayback_app/css/styles.css' %}">
</head>
<body>
    <h1 class="welcome">Welcome to the Wayback App!</h1>
</body>
</html>
```

Open the settings.py file located in the wayback_project folder, and modify the TEMPLATES and STATIC_URL settings as follows:

```python

TEMPLATES = [
    {
        ...
        'APP_DIRS': True,
        ...
    },
]

STATIC_URL = '/static/'
```

You'll also need to add your app to the INSTALLED_APPS setting - it should look something like this:

```python
INSTALLED_APPS = [
    "wayback_app",
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
]
```

Almost there! Now open the views.py file in wayback_app and add the following lines:

```python

from django.shortcuts import render

def home(request):
    return render(request, 'wayback_app/index.html')
```

This code is like a recipe for creating a webpage. It has a function called `home()` that takes a request (like a message) and uses it to put together an HTML page. It uses a Django function called render to take the `index.html` file in the wayback_app folder and put it together into a page for the user to see.

So when someone goes to a certain URL on your website, this code helps create the page that they see. 

Finally, run the development server again using the following command:

    

```
python manage.py runserver
```

Now, when you visit http://localhost:8000/wayback_app/, you should see the "Welcome to the Wayback App!" message, and if your static file is correctly set up, it should be in blue!


![welcome to the wayback app!](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wlfshmtggi0z511n5dbc.PNG)

Ok, that's enough for Part 1 of this series! In the next part we'll build our app, implement some more complex HTML and CSS to make the app more visually pleasing, and package it in a Docker container with all it's dependencies, making it easy to deploy and run on any machine.

Hope you've found this helpful so far, and if you have any questions please ask!

Thanks for reading! 👋