Installing Django in windows 5 - Abhishek Chhibber

Installing Django in Windows through a virtual environment

In this post, I have outline important steps of installing Django framework on Windows 10, using Python 3.5. I have used the command line prompt to create a virtual environment, and installed Django in the same.

 

1) Go to the directory via command prompt

Microsoft Windows [Version 10.0.15063]
(c) 2017 Microsoft Corporation. All rights reserved.

C:\WINDOWS\system32>cd..

C:\Windows>cd..

C:\>E:

 

2) Install virtual environment in the directory

E:\>python -m pip install virtualenv
Collecting virtualenv
 Using cached virtualenv-15.1.0-py2.py3-none-any.whl
Installing collected packages: virtualenv
Successfully installed virtualenv-15.1.0

 

3) Install the virtual environment folder (e.g. venv17) in the virtual environment

E:\>python -m virtualenv venv17
Using base prefix 'C:\\Users\\Abhishek\\AppData\\Local\\Programs\\Python\\Python36-32'
New python executable in E:\venv17\Scripts\python.exe
Installing setuptools, pip, wheel...done.

E:\>

 

4) Go to Scripts folder inside the virtual environment directory (venv17), and activate it

E:\>cd venv17

E:\venv17>cd Scripts

E:\venv17\Scripts>activate

(venv17) E:\venv17\Scripts>

 

(venv17) shows that the virtual environment is now activated

 

5) Come out to venv17 folder. And install Django

(venv17) E:\venv17\Scripts>cd..



(venv17) E:\venv17>pip install django
Collecting django
  Downloading Django-1.11.7-py2.py3-none-any.whl (6.9MB)
    100% |████████████████████████████████| 7.0MB 126kB/s
Collecting pytz (from django)
  Downloading pytz-2017.3-py2.py3-none-any.whl (511kB)
    100% |████████████████████████████████| 512kB 843kB/s
Installing collected packages: pytz, django
Successfully installed django-1.11.7 pytz-2017.3

 

6) Create a new Django Project. This will create a new directory under venv17, named ‘mydjango’

(venv17) E:\venv17>django-admin startproject mydjango

(venv17) E:\venv17>

 

The new directory ‘mydjango’ has the following structure

 

mydjango/
      manage.py
      mydjango/
            __init__.py
            settings.py
            urls.py
            wsgi.py

 

  • manage.py: It is a thin wrapper around the django-admin.py tool, and should not be edited. It is used as a command-line utility to interact with the project.
  • mydjango/: The is the main project directory, and consist of the following files:
  • __init__.py: An empty file that tells Python to treat the mydjango. It should not be edited
  • settings.py: It contains the settings and configurations for the project, including the default setting.
  • urls.py: It contains the URL patterns.
  • wsgi.py: It contains the configuration to run the project, as a WSGI application.

 

Installing Django in windows - Abhishek Chhibber

 

 

Installing Database

7) Creating initial tables in the database

# go to the directory that contains manage.py

 
(venv17) E:\venv17\mydjango>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying sessions.0001_initial... OK

(venv17) E:\venv17\mydjango>

 

The default database is SQLite. In case you want to use MySQL, then go to the setting.py file, and change the database settings, with the following:

# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': your_DB_name,
        'USER': 'youur_user_name',
        'PASSWORD': 'your_password',
        'HOST': 'your_host',
        'OPTIONS': {'charset': 'utf8mb4'},
        'OPTIONS': {
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
        },
    }
}

 

And then make the migrations

 

(venv17) E:\venv17\mydjango>python manage.py makemigrations

 

8) Run the Development Server

(venv17) E:\venv17\mydjango>python manage.py runserver
Performing system checks...


System check identified no issues (0 silenced).
January 06, 2017 - 11:14:39
Django version 1.11.7, using settings 'mydjango.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

 

 

The site can be accessed at http://127.0.0.1:8000/

Installing Django in windows 2 - Abhishek Chhibber

This is a Development, and not Deployment Server.

In order to deploy Django in a production environment, it should be run as a Web Server Gateway Interface (WSGI) application using a real web server such as Apache, Gunicorn, or uWSGI.

 

Creating Admin and Super User

9) Create a Super User

(venv17) E:\venv17\mydjango>python manage.py createsuperuser

Username (leave blank to use 'computer_name'): admin
Email address: ******@gmail.com
Password:
Password (again):
Superuser created successfully.


 

10) Run admin panel

First, run the server

(venv17) E:\venv17\mydjango>python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
January 06, 2017 - 12:55:33
Django version 1.11.7, using settings 'mydjango.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

 

Then go to http://127.0.0.1:8000/admin in the browser

Installing Django in windows 3 - Abhishek Chhibber

Installing Django in windows 4 - Abhishek Chhibber

Creating an Application

 

11) Create an application

 

First, come out of the runserver by pressing control+C / control+break

^C
(venv17) E:\venv17\mydjango>

 

 

Then, create a new app, ‘firstapp’

(venv17) E:\venv17\mydjango>python manage.py startapp firstapp
(venv17) E:\venv17\mydjango>

 

The apps (firstapp) directory is created in the same project directory, which contains the database, and manage.py file.

The directory contains the following:

firstapp/
   migrations/
      _init_.py
   _init_.py
   admin.py
   apps.py
   models.py
   tests.py
   views.py

 

 

models.py file in the app, consists of the models — which are used to create the tables of the database

 

from django.db import models
# Create your models here.

class fin_Trend(models.Model):
       trend = models.CharField(max_length=100)
       class Meta:
               ordering = ('trend',)#this will list the trends in order in the admin panel
       def __str__(self):
              return self.trend

class fin_Country(models.Model):
       country = models.CharField(max_length=100)# a charfield of length 100
       continent = models.CharField(max_length=100)
       class Meta:
               ordering = ('country',)
       def __str__(self):
              return self.country+" : "+self.continent #this will display/return Country:Continent in the admin panel

class fin_News(models.Model):
       news_title = models.CharField(max_length=500)
       news_main_text = models.TextField(blank=True)# a textfield
       news_snippet = models.TextField(blank=True)#this field can be blank
       news_trend = models.ManyToManyField(fin_Trend)
       news_date = models.DateField()
       news_country = models.ManyToManyField(fin_Country) )#this will be inherited from the fin_Country class above, and can have many-to-many fields


       class Meta:
               ordering = ('news_date',)


       def __str__(self):
              return self.news_title


 

Check for Many-to-many and Many-to-one (using ForeignKey) relationships

 

12) Add the app to the main framework

 

Go to the main settings.py file in mydjango > mydjango > setting.py (where the database is added), and add the app name in the ‘installed apps’

 

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'firstapp.apps.FirstappConfig', #Don’t forget to put the comma
]

 

 

In the apps.py file of the fistapp directory, we have the ‘FirstappConfig’ class. We will add the same here.

 

This will make our app active, and connected to our framework.

 

13) Create and apply migrations

(venv17) E:\venv17\mydjango>python manage.py makemigrations

Migrations for 'firstapp':
  firstapp\migrations\0001_initial.py
    - Create model fin_Country
    - Create model fin_News
    - Create model fin_Trend
    - Add field news_trend to fin_news

(venv17) E:\venv17\mydjango>python manage.py migrate

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, firstapp, sessions
Running migrations:
  Applying firstapp.0001_initial... OK

(venv17) E:\venv17\mydjango>

 

Adding models to the admin site

14) Update models.py file

Go to the application (firstapp) > admin.py file, and add the models from the models.py file

from django.contrib import admin

# Register your models here.

from .models import fin_Trend, fin_Country, fin_News # adding all the models

class Fin_News_admin(admin.ModelAdmin):
    list_display = ('id', 'news_title', 'news_date') # display the columns in the admin site
    list_filter = ('news_trend',) # for side filter
    search_fields = ('news_title',) # for search box. should be a list or tuple

class Fin_Country_admin(admin.ModelAdmin):
    list_display = ('id', 'country')
    list_filter = ('country',) # make sure the model names are correct
    search_fields = ('country',)

admin.site.register(fin_News, Fin_News_admin) # register the models
admin.site.register(fin_Trend)
admin.site.register(fin_Country,Fin_Country_admin)

 

Check for migrations, if any (though this has nothing to do with migrations)

 

The admin panel now looks like this:

Installing Django in windows 5 - Abhishek Chhibber

 

After adding some dummy data in Fin_countrys, the filter and search panel, as well as the sorting arrow  are also visible

Installing Django in windows 6 - Abhishek Chhibber

 

 

Editing and Querying models

15) Go to Python shell

(venv17) E:\venv17\mydjango>python manage.py shell


Python 3.6.2 (v3.6.2:5fd33b5, Jul  8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> 

 

We can exit the shell by:

>>> exit()

 

16) Import the models that have to be edited / queried

>>> from firstapp.models import fin_Country
>>> 

 

17) Get all the entries of that model

>>> fin_Country.objects.all()
<QuerySet [<fin_Country: China : Asia>, <fin_Country: France : Europe>, <fin_Country: UK : Europe>, <fin_Country: US : North America>]>
>>> 

 

18) Add a new field

 

# Option 1

>>> 
>>> cont1 = fin_Country()
>>> cont1.country = "India"
>>> cont1.continent = "Asia"
>>> cont1.save()# save is equivalent to commit in SQL

# Option 2
>>> 
>>> cont2 = fin_Country(country = 'South Africa', continent = 'Africa')
>>> cont2.save()
>>> 
>>> 

>>> fin_Country.objects.all()
<QuerySet [<fin_Country: China : Asia>, <fin_Country: France : Europe>, <fin_Country: India : Asia>, <fin_Country: South Africa : Africa>, <fin_Country: UK : Europe>, <fin_Country: US : North America>]>
>>> 
>>> 
>>> len(fin_Country.objects.all())
6
>>> 

 

19) Query Models

 

# Querying all objects

>>> fin_Country.objects.all()
<QuerySet [<fin_Country: China : Asia>, <fin_Country: France : Europe>, <fin_Country: India : Asia>, <fin_Country: South Africa : Africa>, <fin_Country: UK : Europe>, <fin_Country: US : North America>]>
>>> 


# Slicing the objects

>>> fin_Country.objects.all()[:2]
<QuerySet [<fin_Country: China : Asia>, <fin_Country: France : Europe>]>
>>> 


# Using the get method (will work when there is only one result)

>>> fin_Country.objects.get(continent = 'Africa')
<fin_Country: South Africa : Africa>
>>> 


# Using the filter method

>>> 
>>> fin_Country.objects.filter(continent = 'Asia')
<QuerySet [<fin_Country: China : Asia>, <fin_Country: India : Asia>]>
>>> 
>>> 
>>> fin_Country.objects.filter(continent__contains="sia")
<QuerySet [<fin_Country: China : Asia>, <fin_Country: India : Asia>]>
>>> 
>>> 

 

 

20) Connecting data from one model to another

E.g. We will create a News object, which will have trends from the fin_Trend model, and country from the fin_Country model

 

First, we will create an instance, and will add the data, which is not to be connected to that news (title, main text, snippet, date)

 

>>> from firstapp.models import fin_News, fin_Trend, fin_Country
>>> news1 = fin_News()
>>> news1.news_title = "Sample news title"
>>> news1.news_main_text = "This is some text that has been written in the news"
>>> news1.news_snippet = "The news also has snippet"
>>> news1.news_date = “2017-01-01”
>>> news1.save()
>>> 

 

Then, we will find ID of the trend (e.g. collaboration), related to this news, and will add that to this instance

 

 

>>> trnd1 = fin_Trend.objects.get(trend = "Collaboration").id
>>> trnd1
3
>>> news1.news_trend.add(trnd1)
>>> news1.save()
>>> 

 

Similarly, we will add ID of the country (e.g. US), related to this news, and will add that to this instance

>>> cont1 = fin_Country.objects.get(country = "US").id
>>> cont1
1
>>> 
>>> news1.news_country.add(cont1)
>>> news1.save()
>>> 

 

 

If we run the server and check our admin site, we have 1 entry for news, with the filled-in fields

Installing Django in windows 7 - Abhishek Chhibber

 

 

 

Installing Django in windows 8 - Abhishek Chhibber

 

 

We will add two more dummy news to render a list on our web page

 

Creating Views

 

21) Edit views.py

In app > views.py file, import the class from models.py, and then create a views function

 

from django.shortcuts import render
from .models import fin_News # importing the class that needs to be rendered

# Create your views here.

def news_list(request):
       all_news = fin_News.objects.all()
       context = {'all_news':all_news}
       return render(request, 'firstapp/index.html', context)

 

22) Create urls.py file

In the app folder, create a urls.py file, and add the following code:

from django.conf.urls import url
from . import views

urlpatterns = [
    # anything /app/
    url(r'^$', views.news_list, name='index'), ] # news_list is the function of the views.py file

 

 

23) Create templates directory

In the apps directory, create a directory with the name ‘templates’. Within the ‘templates’ directory, create another directory with the app’s name. Within that directory, create index.html

mydjango/
   firstapp/
      templates/
         firstapp/
            index.html

 

In index.html file, add the following:

<h1>Page Heading</h1>

<ul>
       {% for news in all_news%}
              <li>{{news.news_title}}</li> # {{ }} is for print
       {% endfor %}
</ul>

 

If we go to http://127.0.0.1:8000/firstapp/, we get the web page index.html

 

Installing Django in windows 9 - Abhishek Chhibber