top of page
blog_cover.png

BLOG

How to Create a Virtual environment and Setup Django project

Django is a Web framework written in Python. A Web framework

is a software that supports the development of dynamic Web sites, applications,

and services. It provides a set of tools and functionalities that solves many common

problems associated with Web development, such as security features, database access, sessions,

template processing, URL routing, internationalization, localization, and much more.

How to Create a Virtual environment and Setup Django project

Table of Topics:

A few of its applications are given below.

  • Why Django?

  • Who’s Using Django?

  • COVID-19 diagnosis

  • Install Virtual environment

  • Install requirements inside virtual environment

  • Setup/Create a Django Project

  • Benefits of Django

  • Conclusion

Why Django?

Django is a Web framework written in Python. A Web framework is a software that supports the development
of dynamic
Web sites, applications, and services. It provides a set of tools and functionalities that solves many common problems associated with Web development, such as security features, database access, sessions,
template processing, URL routing, internationalization, localization, and much more. 
Using a Web framework,
such as Django, enables us to develop secure and reliable Web applications very quickly in a standardized way, without having to reinvent the wheel.

Who’s Using Django?

It’s good to know who is using Django out there, so to have an idea what you can do with it.

Among the biggest Web sites using Django we have: Instagram, Disqus, Mozilla, Bitbucket.

Installation:

The first thing we need to do is install some programs on our machine so to be able to start playing with Django.

The basic setup consists of installing Python, Virtual env, and Django.

Using virtual environments is not mandatory, but it’s highly recommended. If you are just getting started,

it’s better to start with the right foot. When developing Web sites or Web projects with Django, it’s very common to have to install external libraries to support

the development. Using virtual environments, each project you develop will have its isolated environment. So, the dependencies won’t clash. It also allows you to maintain in your local machine projects that run on different Django versions.

Go to www.python.org click on the Python 3.6.2 download page, scroll down until you see the download files listed below:

blog7_pic1.png

Go to your Downloads directory, right click on the installer and click on Run as administrator.

blog7_pic2.jpg

Make sure you check the option Add Python 3.6 to PATH and click on the Install Now option.

blog7_pic3.jpg

Now search for the Command Prompt program and open it and type following command:

python --version

Great, Python is up and running. Next step: Virtual Environments!

Install Virtual environment:

For the next step, we are going to use pip, a tool to manage and install Python packages, to install virtualenv.

In the Command Prompt, execute the command below:

blog7_pic4.jpg

If it is already installed, it will show requirement already satisfied.

So far the installations that we performed were system-wide. From now on, everything we install, including Django itself,

will be installed inside a Virtual Environment.

​

Think of it like this: for each Django project you start, you will first create a Virtual Environment for it. It’s like having a sandbox for each Django project. So you can play around, install packages, uninstall packages without breaking anything.

​

Let’s start by creating a new folder with the name Development folder. Since this is going to be our very first project,

we don’t need to pick a fancy name or anything. For now, we can create a new folder under the Development folder

and call it myproject.

Run below commands:

mkdir myproject1

cd myproject1

blog7_pic5.jpg

This folder is the higher level directory that will store all the files and things related to our Django project, including its virtual environment.

So let’s start by creating our very first virtual environment and installing Django.

Inside the myproject1 folder: virtualenv venv

blog7_pic6.jpg

Our virtual environment is created. Now before we start using it, we need to activate:

venv\Scripts\activate

You will know it worked if you see (venv) in front of the command line, like this:

blog7_pic6.jpg

Let’s try to understand what happened here. We created a special folder named venv. It contains a copy of Python inside this folder. After we activated the venv environment, when we run the python command, it will use our local copy, stored inside venv, instead of the other one we installed earlier.

​

Another important thing is that the pip program is already installed as well, and when we use it to install a Python package, like Django, it will be installed inside the venv environment.

​

Install requirements inside virtualenv:

Setup a Django Project:

​

Install Django :

pip install django

Create a new Django project:

To start a new Django project, run the command below:

​

django-admin startproject myproject

​

The command-line utility django-admin is automatically installed with Django.

​

After we run the command above, it will generate the base folder structure for a Django project.

Right now, our myproject directory looks like this:

myproject1/ <-- higher level folder

|-- myproject/ <-- django project folder

| | |-- __init__.py

| | |-- settings.py

| | |-- urls.py

| | |-- wsgi.py

| +-- manage.py

+-- venv/ <-- virtual environment folder

  Our initial project structure is composed of five files:

  • manage.py: a shortcut to use the django-admin command-line utility. It’s used to run management commands related to our project. We will use it to run the development server, run tests, create migrations and much more.

​

  • __init__.py: this empty file tells Python that this folder is a Python package.

​

  • settings.py: this file contains all the project’s configuration. We will refer to this file all the time!

​

  • urls.py: this file is responsible for mapping the routes and paths in our project. For example, if you want to show something in the URL /about/, you have to map it here first.

​​

  • wsgi.py: this file is a simple gateway interface used for deployment. You don’t have to bother about it. Just let it be for now.

      For now, you can ignore the migration errors; we will get to that later.

Now open the following URL in a Web browser: http://127.0.0.1:8000 and you should see the following page:

blog7_pic7.jpg

Navigate to sampleapi:

cd myproject

  Django Apps:

   In the Django philosophy we have two important concepts:

  • app: is a Web application that does something. An app usually is composed of a set of models (database tables), views, templates, tests.

  • project: is a collection of configurations and apps. One project can be composed of multiple apps, or a single app.

Start a new app:

Pyhon manage.py startapp firstapp

Here is what your project structure should look like:

Notice that we used the command startapp this time.

This will give us the following directory structure:

myproject1/

|-- myproject/

| |-- firstapp/ <-- our new django app!

| | |-- migrations/

| | | +-- __init__.py

| | |-- __init__.py

| | |-- admin.py

| | |-- apps.py

| | |-- models.py

| | |-- tests.py

| | +-- views.py

| |-- myproject/

| | |-- __init__.py

| | |-- settings.py

| | |-- urls.py

| | |-- wsgi.py

| +-- manage.py

+-- venv/

   So, let’s first explore what each file does:

​

  • migrations/: here Django store some files to keep track of the changes you create in the models.py file, so to keep the database and the models.py synchronized.

​

  • admin.py: this is a configuration file for a built-in Django app called Django Admin.

​

  • apps.py: this is a configuration file of the app itself.

​

  • models.py: here is where we define the entities of our Web application. The models are translated automatically by Django into database tables.

​

  • tests.py: this file is used to write unit tests for the app.

​

  • views.py: this is the file where we handle the request/response cycle of our Web application.

​

Now that we created our first app, let’s configure our project to use it.

Add the firstapp app to the INSTALLED_APPS, inside the settings.py module

# Application definition

INSTALLED_APPS = [

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'firstapp',

]

Hello ! world

Let’s write our first view. We will explore it in great detail in the next tutorial. But for now, let’s just experiment how it looks like to create a new page with Django.

​

Open the views.py file inside the boards app, and add the following code:

views.py

from django.http import HttpResponse

def home(request):

return HttpResponse('Hello, World!')

​

Views are Python functions that receive an HttpRequest object and returns an HttpResponse object. Receive a request as

a parameter and returns a response as a result. That’s the flow you have to keep in mind!

​

So, here we defined a simple view called home which simply returns a message saying Hello, World!.

Now we have to tell Django when to serve this view. It’s done inside the urls.py file:

​

urls.py

​

from django.conf.urls import url

from django.contrib import admin

from boards import views

urlpatterns = [

url(r'^$', views.home, name='home'),

url(r'^admin/', admin.site.urls),

]

Let’s see what happen when you run below command:

In a Web browser, open the http://127.0.0.1:8000 URL:

blog7_pic8.jpg

That’s it! You just created your very first view.

Benefits of Django:

​

1. Django has the Model View Template Architecture:

Django has a Model-View-Template (MVT) architecture. The MVT (Model View Template) is a software design pattern. It is a collection of three essential components Model, View, and Template. These three layers are responsible for different things and can be used independently.

​

The Model helps to handle database. It is a data access layer, which contains the required fields and behaviors of the data you’re storing. There’s hardly an application without a database. The Django framework officially supports four databases, namely, PostgreSQL, MySQL, SQLite, and Oracle.

​

A model is a Python class, and it does not know anything about other Django layers. An application programming interface (API) is the only means used to communicate between layers.

​

Models help developers to create, read, update, and delete objects (CRUD operations) in the original database. Also, they hold business logic, custom methods, properties, and other things related to data manipulation.

​

It accepts HTTP requests, applies business logic provided by Python classes and methods, and provides HTTP responses to the client requests.

​

​

2. Django is Highly Secure:

When we make web applications in Django, it makes sure that developers don’t commit any mistakes related to security. It will be pretty difficult to find security loopholes in Django, even in the user authentication system.

​

The framework has protection against the most common security attacks like XSS and CSRF (Cross-Site Request Forgery) attacks, SQL injections, Clickjacking, etc. The user authentication system of Django is also solid, to manage usernames and passwords.

​

While transmitting data, Django automatically encrypts the passwords and all the essential information with a security key.

​

​

3. Django Provides a Default Admin Panel:

Django automatically comes up with an admin interface. You don’t need to write any code to create it. Django gives you everything by default and hence reduces a lot of development time.

blog7_pic9.jpg

4. Django is good for Search Engine Optimization (SEO):

Django offers several useful SEO tools. Django provides a module called the Django SEO framework, which developers can use to reduce page loading time by using cached templates and compressing CSS and JavaScript.

​

Django even provides a tool to manage robots.txt. However, it may not be as good as WordPress (the most used CMS software for blogging) when it comes to SEO. But Django is one of the best frameworks for search engine optimization, compared to other web development frameworks.

​

​

5. Django Provides Object Relational Mapper (ORM):

Django ORM provides an elegant and powerful way to interact with the database in an Object-Oriented fashion. ORM is a library that automatically transfers data stored in databases into objects commonly used in application code.

​

You don’t need to write specific SQL queries to create tables and insert data. When a class is defined, ORM generates a table for the class automatically. This table contains fields for all the variables inside the class. Also, the table adds rows automatically when we create objects.

​

ORM is an excellent concept by which you can directly create tables using classes and add data with the help of objects of the class.

​

The ability of the Django ORM to extract information speeds up the web application development process. It also helps developers to make working prototypes in no time.

​

​

6. Django is Highly Scalable:

It is yet another benefit of using Django for building web apps. Depending on your specific product requirements, development can be scaled up or down, altering the number and complexity of Django components as necessary.

​

Django can handle any hardware additions. Also, it is capable of meeting massive traffic demands. It is the main reason why websites like Instagram, Pinterest, Disqus, etc., use the Django framework.

​

Django can handle traffic and mobile app API usage of more than 400 million users, helping maximize scalability and minimize web hosting costs. Many third-party applications come with Django. These applications can be integrated, depending on project requirements.

​

This scalability of Django makes it one of the best choices for many large-scale web applications in the software world.

​

​

7. Batteries Included:

Django prides itself as a batteries-included framework. What that means is that it comes with a lot of stuff out of the box, that you may or may not use depending on your application. Instead of having to write your own code (the power), you just need to import the packages that you want to use.

​

It’s a part of the convention over configuration paradigm that Django is part of, and it allows you to make use of the solutions implemented by world-class professionals.

​

​

Conclusions:

Django is the best framework for web applications, as it allows developers to use modules for faster development. As a developer, you can make use of these modules to create apps, websites from an existing source. It speeds up the development process greatly, as you do not have to code everything from scratch.

​

Django follows the Don’t Repeat Yourself (DRY) principle, making this framework time-efficient. In other words, there’s no need to rewrite existing code because Django allows you to assemble your website like a Lego set. The framework is well-suited for high load systems and can decrease development time thanks to lots of helper objects. This is due to the architecture, which we’ll have a closer look at below.

Sudharshan Reddy

​Kushagramati

Sudharshan Reddy.jpg
bottom of page