X

Get Started with Visual Studio Code with Python Django

VsCode-with-Python-Django

Visual Studio Code with Python Django

I wanted to continue on my python exploration and show how to get started with Visual Studio Code with Python Django.
What is Django you may ask ? Not the movie for sure.

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source.
https://www.djangoproject.com/

Basically you can think of Django somewhat like WebApi plus Entity Framework together, since Django provides an ORM with the framework.

First thing first, in python we should set up our virtualenv such that we have a dev environment and don’t pollute our global space with our packages. You should already have pip install with your python if you are using the Python 3.x series.

Open up your powershell or command prompt and type

PS C:\Users\flask-sample> pip install virtualenv
Collecting virtualenv
  Downloading virtualenv-15.1.0-py2.py3-none-any.whl (1.8MB)
    100% |################################| 1.8MB 325kB/s
Installing collected packages: virtualenv
Successfully installed virtualenv-15.1.0

Once you have virtualenv we will need virtualenvwrapper-win since we are running under windows.

PS C:\Users\flask-sample> pip install virtualenvwrapper-win
Collecting virtualenvwrapper-win
  Downloading virtualenvwrapper-win-1.2.1.zip
Requirement already satisfied: virtualenv in c:\users\taswar\appdata\local\programs\python\python35-32\lib\site-packages
 (from virtualenvwrapper-win)
Installing collected packages: virtualenvwrapper-win
  Running setup.py install for virtualenvwrapper-win ... done
Successfully installed virtualenvwrapper-win-1.2.1

Below is a sample gif of the interaction.
Install virtualenvwrapper-win

Now we need to create the virtualenv that we will be using.

PS C:\Users\django-sample> mkvirtualenv DjangoProject
Using base prefix 'c:\\users\\taswar\\appdata\\local\\programs\\python\\python35-32'
New python executable in C:\Users\taswar\Envs\DjangoProject\Scripts\python.exe
Installing setuptools, pip, wheel...done.

This will create your virtualenv inside your home directory for mine it is under

PS C:\Users\taswar\Envs\DjangoProject\

In order to activate the virtualenv we need to use the activate.ps1 script but you must make sure we have the correct execution-policy in your powershell but before we do that lets launch our Vscode

PS C:\Users\taswar\Documents\GitHub\>mkdir djangoExample
PS C:\Users\taswar\Documents\GitHub\>cd djangoExample
PS C:\Users\taswar\Documents\GitHub\djangoExample>code .
#Once in your vscode launch your command powershell prompt Ctrl+Shift+`

Below is an example of using powershell to do the above action

django project in powershell

You may want to set your terminal correctly in vscode like below.

djangoProjectCodeTerminal

Lets now set up our directory to use the virtualenv, remember the Set-ExecutionPolicy for powershell and use the terminal inside your vscode with Ctrl+Shift+` (right tick)

PS C:\Users\taswar\Documents\GitHub\djangoExample> C:\Users\taswar\Envs\DjangoProject\Scripts\activate.ps1
(DjangoProject) PS C:\Users\taswar\Documents\GitHub\djangoExample>
#one can set the project also
(DjangoProject) PS C:\Users\taswar\Documents\GitHub\djangoExample> setprojectdir .

    "C:\Users\taswar\Documents\GitHub\djangoExample" is now the project directory for
    virtualenv "C:\Users\taswar\Envs\DjangoProject"

    "C:\Users\taswar\Documents\GitHub\djangoExample" added to
    C:\Users\taswar\Envs\DjangoProject\Lib\site-packages\virtualenv_path_extensions.pth

Lets now install Django

#now lets install Django
(DjangoProject) PS C:\Users\taswar\Documents\GitHub\djangoExample> pip install django
Collecting django
  Using cached Django-1.11.1-py2.py3-none-any.whl
Collecting pytz (from django)
  Using cached pytz-2017.2-py2.py3-none-any.whl
Installing collected packages: pytz, django
Successfully installed django-1.11.1 pytz-2017.2

Lets now create a our first Django project.

(DjangoProject) PS C:\Users\taswar\Documents\GitHub\djangoExample> django-admin.py startproject HelloWorld
PS> cd HelloWorld
PS> ls 
Directory: C:\Users\taswar\Documents\GitHub\djangoExample\HelloWorld


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----         11/6/2016   2:39 PM                HelloWorld
-a----         11/6/2016   2:39 PM            830 manage.py



    Directory: C:\Users\taswar\Documents\GitHub\djangoExample\HelloWorld\HelloWorld


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----         11/6/2016   2:39 PM           3228 settings.py
-a----         11/6/2016   2:39 PM            788 urls.py
-a----         11/6/2016   2:39 PM            414 wsgi.py
-a----         11/6/2016   2:39 PM              0 __init__.py

Note: That we in the root folder manage.py file inside the HelloWorld folder there is another HelloWorld project which contains.

  1. settings.py: Setting is the configuration for this Django project. The file contains all apps, database settings information.
  2. urls.py: The url declarations for this Django project, kind of like the url routes you have in WebApi in global.ascx.cs file, which can list all your urls.
  3. wsgi.py: This is the entry-point for WSGI-compatible web servers to serve the project.
  4. __init__.py: Is an empty file, to signal to Python that this is a Python package.

The image below shows the process of above commands in VSCode.

Setting up Django in VSCode

Running Django

In order to run our django application we can type

PS> python manage.py runserver

This will start the django server.

VsCode-with-Python-Django-1

Creating our HelloWorld App

Now that we have django up and running we need to create our first app. Hmm have we not create the app yet? Well in Django what we have done so far is we have created a project for Django but we have not created an App yet.
What is the difference between an App and Project then?

What’s the difference between a project and an app? An app is a Web application that does something – e.g., a Weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular website. A project can contain multiple apps. An app can be in multiple projects.
https://docs.djangoproject.com/en/1.11/intro/tutorial01/

Lets get started to create an HelloWorldApp

PS> django-admin startapp HelloWorldApp
PS> cd HelloWorldApp
PS> ls HelloWorldApp
Directory: C:\Users\taswar\Documents\GitHub\djangoExample\HelloWorld\HelloWorldApp


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----         11/6/2016   3:14 PM                migrations
-a----         11/6/2016   3:14 PM             66 admin.py
-a----         11/6/2016   3:14 PM            106 apps.py
-a----         11/6/2016   3:14 PM             60 models.py
-a----         11/6/2016   3:14 PM             63 tests.py
-a----         11/6/2016   3:14 PM             66 views.py
-a----         11/6/2016   3:14 PM              0 __init__.py

Lets now edit our settings.py under HelloWorld such that we can add the HelloWorldApp into it. Open settings.py in VSCode, and look for INSTALLED_APPS, append our HelloWorldApp to the list (Note the command at the end)

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'HelloWorldApp',
]

Now let’s modify the urls.py under the HelloWorld project directory.

from django.conf.urls import url
from django.contrib import admin
from HelloWorldApp.views import bar


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'HelloWorldApp/$', bar),
]

Now lets modify views.py under HelloWorldApp app directory

from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
def bar(request):
    return HttpResponse("Hello World!")

We can now run our app

python manage.py runserver

When everything is up and running you should be able to go to Chrome or your favorite browser and view port 8000 and see Hello world there.

VsCode-with-Python-Django-2

Hope this helps you in setting up vscode with development of Python Django.

To learn about running VSCode with python read my previous post on
Getting Started with Visual Studio Code with Python.

Also my post on Flask
Getting Started with Visual Studio Code with Python

Categories: VSCode
Taswar Bhatti:

View Comments (12)

  • do i necessarily have to use my VSc terminal. i am confused about what to use properly, because i would prefer to use my CDM, but my files are always opening up in powershell. how do i change this? please help out

  • am stuck. when i am done creating the "/djangoExample>code": and i proceed to execute the command. i am taken to the VSc terminal but when i use the ""Cntrl + Shift +` "", nothing does happen. the following code does not work. what could be the problem??

    • I have added some gif video for you to follow through maybe that will help. I think the issue you may be having with vscode could be that your terminal is not set up properly. Check the blog post again you should see some gif that may help you.

  • I realised in oneof your steps of installing Django you have a path2 of; [ "C..../Documents/Github>" ] is this to your github respository or its just a named folder??

    • just the name of a folder where i store most of my projects. I usually make them into github projects afterwards, you can use any other folders.

  • I can't get django to install into the new directory I set in Git.
    Because when I do pip install django, the directory remains empty.
    I have tried creating a new project and I get the same result.
    It installs in \Envs\, and I also can't find the manage.py file,
    so I can't launch the server.

  • Response to others. I went over the instructions 6 times and nothing.
    The reason is that

    django-admin.py startproject HelloWorld

    does nothing. I had to do the following:

    django-admin startproject HelloWorld

    • Hi Ram so can I assume that you have resolved the issue by just not typing the extension .py?

  • Yes taswar,

    I resolved the issue.
    I had another issue with printing HelloWorld.

    NameError: name 'url' is not defined
    And when I change to path (because the default admin/ is written with that, it then says bar not defined.
    Didn't figure that one out.

  • Thanks, this tutorial worked great. I struggled a bit, but that was my fault. I wasn't doing: cd HelloWorld before running django-admin.py etc. Once I figured out my problem this worked great.

    Thank you for the write-up.

Related Post