Jungletronics
Published in

Jungletronics

Django MTV In VS Code

How To Install Django Inside Virtual VS Code— DjangoSeries Episode # 01

Welcome! in this post we will see how to set up the Visual Studio Code for writing and executing a Django Application on Windows 10.

As in the first Episode of #DjangoSeries, published some time ago, we used Atom, but let’s start Django App all over again, from the scratch, using VS Code instead.

Motivation:

VS code incorporates awesome extensions to make it efficient and seamless in using Django in Python.

Are you curious about Django MVT?

MVT stands for Model, View, and Template architecture.

Django is based on MVT (Model-View-Template) architecture. MVT is a software design pattern for developing a web application. Model: The model is going to act as the interface of your data. It is responsible for maintaining data. View: The View is the user interface — what you see in your browser when you render a website. It is represented by HTML/CSS/Javascript and some other files; Template: A template consists of static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted.

LET’S START ALL OVER AGAIN!

00#Step — You Will need to be installed on your computer:

visualstudio.comanaconda

Just run VS Code and Anaconda Nucleus installers. Use defaults, not a big deal, right?

Open the VS Code, and this screen appears:

VS Code welcome page \o/

01#Step — So now first let install this extension: Python (MS)

First extension— Python(MS)

What are Python’s Visual Studio Code extension features?

IntelliSense (Pylance — auto-completion), linting (style-error-checker), debugging, code navigation, code formatting, refactoring, variable explorer, test explorer, and more!

Last but not least is the Jupyter extension! it works together to give you a great Notebook experience in VS Code. That’s great, right?

02#Step —Close Vs Code and Go To Your Windows 10 Start menu and Let’s create working Django Directory — Type:

command prompt

or Press Win + R to open the Run box, then type cmd and hit Enter to open it. Type:

cd Desktopmkdir django_projectscd django_projectscode .

This will open VS Code instantly in the DJANGO PROJECTS folder \o/

Now you can close vanilla win prompter ;)

03#Step — Inside VS Code, Let’s use Command Prompt instead of PowerShell.

Changing the Shell and Activating Command Prompt v.10

Note: conda environments cannot be automatically activated in the integrated terminal if PowerShell is set as the integrated shell. See Integrated terminal — Configuration for how to change the shell.

04#Step — Now, Install Code Runner extension: It offers buttons to easily run the code. An essential Hand Tool Every IDE Should Offer, right?

Second extension: Code Runner

05#Step — Install Pylint extension — It will check for standards and duplicated code.

To install it in windows, just type the following command in your command line or VS Code Terminal:

pip install pylint
Running pip install pylint

06#Step — Let’s make some configurations right away: Go to Manage(settings), click these buttons and type the snippet below:

Click this icon, at the button right corner of VS Code (or Ctrl + ,) then Settings
…and Open Settings (UI).

Let’s enjoy this settings.json file, and install these tools too: In addition to pylint, already installed, let’s install mypy (a linter — an optional static type checker), flake8 (it checks your codebase against coding style — PEP8), and unit test (It determines and ascertains the quality of your code).

For this copy/paste this chunk code:

This makes Code Runner use the Terminal, instead of output, and we will not use selections and ask to install mypy and flake8 and unit test…confirm everything! …oops, there is more: it formats your code (PEP8) as soon as you type Ctrl + S 😍 very convenient isn’t it? 👌
This config will make your life easier, and when you save your code, it makes your code more pythonic, using PEP8. This will make you write code like a real pro!

07#Step — Now you will need to point to your Python installation.

To see where Python is installed on your machine, type:

where.exe pythonMicrosoft Windows [versão 10.0.19042.1415]
(c) Microsoft Corporation. Todos os direitos reservados.
C:\Users\giljr\Desktop\django_projects>where.exe python
C:\Users\giljr\anaconda3\python.exe
C:\Users\giljr\AppData\Local\Microsoft\WindowsApps\python.exe

Let’s create a main.py file in the root directory and VS Code will ask you:

Click Select Python Interpreter blue button…
…choose Your Python Interpreter (mine is from Conda), and you will see at the left corner of VS Code:
For now, I will use Python from Anaconda, see at the bottom right corners of the IDE.

08#Step — On terminals, run these commands (which buttons show up):

It asks: Linter mypy is not installed. Install? and Linter flake8 is not installed, Install? Click Install for both :)

If the VS Code doesn’t ask :/

pip install pylint
pip install formatter autopep8
pip install flake8
pip install mypy
pip install unittest2

09#Step — Go to Terminal and let’ s create a Virtual Environment. Type:

python -m venv djangoEnv

This will create another directory, that your VM will running inside.

If it asks you, install for both and run 👍pip install — upgrade pip👏

10#Step — Go to Terminal and type:

djangoEnv\Scripts\activate
python -m pip install --upgrade pip

Now Django:

python -m pip install django

This will activate the virtual environment, update the pip and install Django machinery.

To confirming, Type:

python -m django --version4.0

Congratulations! Django 4.0 is ready to go in you djangoEnv!

When You want to deactivate your virtual machine, type:

djangoEnv\Scripts\deactivate

Just in case, as we will set up an extension to make this activation automatic for us.

11#Step — To do this let’s create our local configuration: create a directory by clicking DJANGO PROJECT, and call it .vscode and inside it create a file called settings.json:

Copy/paste this snippet below…

Or copy and paste from here (adjust for your directories, please😜):

{
"python.pythonPath": "C:/Users/<your_profile>/<your_projects_dir>/djangoEnv",
"code-runner.executorMap": {
"python": "C:/Users/<your_profile>/<your_projects_dir>/djangoEnv",
}
}

12#Step — To Activate your Django Environment VM, Type:

Microsoft Windows [versão 10.0.19042.1466]
(c) Microsoft Corporation. Todos os direitos reservados.
C:/.../<your_projects_dir>djangoEnv\Scripts\activate(djangoEnv) C:\Users\giljr\new_django>

Once you did it you can kill the Terminal at any time and open it again and automatically djangoEnv will be loaded for you — This feature is really handy 👌 thanks to json file above.

13#Step — Create a main.py inside your DJANGO_PROJECT:

This command will say Code Runner to automatically activate the virtual environment.

Click on all blue buttons to brings PEP8, mypy and flake8.

14#Step — Now, finally, Django Turn! Let’s Start our Django Project:

Go to Terminal and type:

django-admin startproject first_project

This will create a new first-project directory, like this:

VS Code’s first_project folder’s files — see descriptions on table I below
Table I — Django Project Folders’ Files Descriptions

15#Step — Let’s use manage.py now:

Change to first_project directory and type on Terminal:

cd first_project
python manage.py runserver

Here is the output:

Pasting it here, for your convenience 😜:

django-admin startproject first_project(djangoEnv) C:\Users\giljr\Desktop\django_projects>cd first_project(djangoEnv) C:\Users\giljr\Desktop\django_projects\first_project>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
December 26, 2021 - 18:38:34
Django version 4.0, using settings 'first_project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[26/Dec/2021 18:39:06] "GET / HTTP/1.1" 200 10697
[26/Dec/2021 18:39:06] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423
[26/Dec/2021 18:39:07] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 86184
[26/Dec/2021 18:39:07] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 85876[26/Dec/2021 18:39:07] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 85692
Not Found: /favicon.ico
[26/Dec/2021 18:39:07] "GET /favicon.ico HTTP/1.1" 404 2117
[26/Dec/2021 18:39:21] "GET / HTTP/1.1" 200 10697

16#Step — Go To http://127.0.0.1:8000/

There you have it!
Fig 8. Congratulations! There you have it in your browser: your first django app!

Now let’s talk about Migrations and Django Application.

As you can see (output above) there is a warning about 18 unapplied migrations.

Migration allows you to move databases from one design to another, this is also reversible.

So you can migrate your database anytime.

For now, you can ignore this warning.

Let’s continue and create our first Hello World Django Application.

Inside your project folder, you can have any number of applications. Awesome, right?

Let’s get some terminology straight about Django:

Table II — Django Terminologies Descriptions

17#Step — Let’s create our simple first app with this script:

Ctrl+c to stop the server (and cls to clean console), and type:

python manage.py startapp first_app
VS Code’s First_App & First_Project’s Files created by the Fantastic Django machinery!

As you can see it will create other directories inside first_project directory.

Let’s see what do these files mean:

Table III — Django Application Folders’ Files Descriptions

18#Step — Now let’s learn the process of creating a view and mapping it to a URL!

Go To your VS Code and open the first_project/settings.py file, and type:

(...)
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'first_app'
]

This will registrate your app inside your first project.

19#Step — Now open first_app/views.py and type:

from django.shortcuts import renderfrom django.http import HttpResponse# Create your views here.def home(request):
return HttpResponse("Hello, Django!\nWe've got to home website access!")
def welcome(request):
return HttpResponse('This is my First Django Welcome Page! Welcome!!!')

20#Step — Go To your application, and create a new file (urls.py):

first_app/urls.py and save it like this:

from django.urls import pathfrom first_app import viewsurlpatterns = [path("", views.home, name="home"),]

This is a modular configuration. Inside your first_project/urls.py we will call to include it. This code pulls in the app’s first_app/urls.py using django.urls.include, which keeps the app's routes contained within the app. This separation is helpful when a project contains multiple apps.

Each view must return a HttpResponse return.

Django Web-Framework Architecture (Front + Backend)

21#Step — Now map this view in the the first_project/urls.py file:

from django.contrib import admin
from django.urls import path
from first_app import views
urlpatterns = [
path("", include("first_app.urls")),
path('welcome/', views.welcome, name='welcome')
path('admin/', admin.site.urls),
]

Finally just call the server again:)

python manage.py runserver

And Go To your browser and point it to:

http://127.0.0.1:8000/

or

localhost:8000

And here is the page:

or

http://127.0.0.1:8000/welcome/

And here is the page:

Your Hello World First Application Running Beautifully \o/

Now, we have a Django project and 1 app running beautifully! as well as all convenient 😎services of Django 👌

Accessing http://127.0.0.1:8000/admin

That’s all for today!

See you soon at the next Django Episode o/

Now, Reminders:0 - django-admin startproject first_project (step#13)

cd first_project
python manage.py runserver (step#14) localhost:8000

Ctrl + C (stops server)
1 - python manage.py startapp first_app (step#16)2 - Register your app in first_project (step#17)
settings.py at INSTALLED_APPS list;
3 - From first_app views.py create methods to handle the request:
from django.http import HtttpResponse (step#18)

# Create your views here.
def method_name(request):
return HtttpResponse('Your_Message_Goes_Here')
4 - Create a File first_project/urls.py (step#19)5 - Map the view to first_project urls.py: (step#20)

from first_app import views
urlpatterns = [
path("", include("your_app.urls")), path('method_name/', views.method_name),
path('admin/', admin.site.urls),
]
6 - python manage.py runserver

👉 git

👉gdrive

Inside Django file there is a readMe.txt:

References & Credits

Django Tutorial in Visual Studio Code (VS official)

Django (web framework)

Using Python environments in VS Code

Django App — Quick install guide

PEP 8 — Style Guide for Python Code

Code Runner

How can I find where Python is installed on Windows?

Django Project MVT Structure

visualstudio.com

Best Visual Studio Code Extensions for Python/Django

Conda

Anaconda Installers

Another Python Template Engine — Jinja

Edited: jan 29, 2021 — add step#12 — activation of djangoEnv

Related Posts

Related Posts

00#Episode — DjangoSerie — Django Intro — How To Build your First App in Python Django Framework — DjangoSeries

01#Episode — DjangoSerie — Django MTV In VS Code — How To Install Django Inside Virtual VS Code (this one :)

02#Episode — DjangoSerie — Can You Solve This in Python? — Here is A Basic Python Question!

03#Episode — DjangoSerie — JUNGLE-DJANGO Webpage! This Is My New Django Netflix Clone Page!

04#Episode — DjangoSerie — A Django Blog In VS Code — Quick Start!Part_I

05#Episode — DjangoSerie — A Django Blog In VS Code — Database, Migrations & Queries — Part_II

06#Episode — DjangoSerie — A Django Blog In VS Code — Bootstrap, Tailwind CSS — Part_III

07#Episode — DjangoSerie — A Django Blog In VS Code — Forms & Validations — Part_IV

08#Episode — DjangoSerie — A Django Blog In VS Code — Login & Logout — Part_V

09#Episode — DjangoSerie — A Django Blog In VS Code — Upload Profile Picture — Part_VI

10#Episode — DjangoSerie — A Django Blog In VS Code — Update & Resize Picture — Part_VII

11#Episode — DjangoSerie — A Django Blog In VS Code — Class-Based-View & CRUD — Part_VIII

12#Episode — DjangoSerie — A Django Blog In VS Code — Posts Pagination & Quick DB Population — Part_IX

13#Episode — DjangoSerie — A Django Blog In VS Code — Self-Service Django Password Reset — Part_X

14#Episode — DjangoSerie — A Django Blog In VS Code — Heroku Deploy — How To Push Your Site To Productio — Part_XI

Let me tell you something …

This post takes me a great effort.

It was made with love. Follow it fully… it takes patience and perseverance. This way, by repeating this experiment, you can collaborate with us to have a safe and up-to-date source of reference for Django at VS Code.

Thank you very much!

First published at Dec, 2021

Yesterday is history, tomorrow is a mystery, today is God’s gift, that’s why we call it the present.

Joan Rivers

--

--

--

J of Jungle + 3 Plats Arduino/RPi/Pic = J3

Recommended from Medium

Voice2Voice Translation, Tone-of-Voice Control, Event Calendar, and more!

How to prepare for AWS SysOps certification exam?

Deploy a Spring Boot Application Into Kubernetes

#bigdata 29e — NoSQL with Base, Cassandra and MongDB

Week11 — News, Updates & Reminders — AWS | HashiCorp | Istio | Kubernetes | Linux

Tech News, Updates and Press Conference

Web Scraping Tutorial #7 — Scrape most-active stock data in market using python & playwright…

Why We Need Crappy Software Architecture

Docker & Kubernetes Overview

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
J3

J3

Hi, Guys o/ I am J3! I am just a hobby-dev, playing around with Python, Django, Lego, Arduino, Raspy, PIC, AI… Welcome! Join us!

More from Medium

A Django Blog In VS Code — Database Migrations & Queries

What is Django?

Django Tutorial: Getting started.

Markdown2 + Django

Django & Markdown Part 2 (installing an editor)