Why is it so crucial to have a virtual environment in a Django project?
The virtual environment is similar to a library.

Why is it so crucial to have a virtual environment in a Django project?

What is virtual environment?

It keep track of the python package and additional packages that are required for a certain project.

To better understand the concept of virtual environment, we'll use the example of a library. By comparing the library, the workflow of the virtual environment is explained in the table below. From the below example, lets assume that,

  1. Library as system
  2. History, Science section as Virtual environment
  3. Reader as Project
  4. Books related to history as packages installed for a particular project

No alt text provided for this image

Assume that we have "Project A" in our system, which runs on Django 3.0. Django 4.0 was installed globally in our system. Unless we activate virtual environment for "Project A", it automatically uses Django 4.0 which was installed globally in our system. Django 4.0 is an updated version with new features. Our "Project A" is built using Django 3.0. If we use Django 4.0 to run "Project A." The upgraded features are regarded as error.

For instance, If the "Project A" runs on Django 3.0, it shows the following error. ImportError: cannot import name 'ugettext_lazy' from 'django.utils.translation, because In Django 4.0 "ugettext_lazy" is removed, you need to import below library. from django.utils.translation import gettext_lazy as _


How to Create virtual environment in Windows?

  1. To create virtual environment, use the below command in terminal py -m venv denv Here denv is virtual environment name, it is user defined name
  2. To activate virtual environment, type the below command in terminal denv\Scripts\activate.bat

After creating virtual environment, we have virtual environment folder for our project

No alt text provided for this image

Importance of requirements.txt:

We have already denv(virtual environment). If you want to delete it, rebuild it, install only the packages you need, and then run pip freeze > requirements.txt to produce a file with only the packages you need. After executing the above command, it creates requirements.txt file. In that file, we can see all the dependencies required for our project.

No alt text provided for this image

To install all the above dependencies for the virtual environment, we can use pip install -r requirements.txt

Note:

This is my first piece of article. I've included all of the information about virtual environments that I'm aware of. This article is intended for beginners. Please let me know if you notice any errors in this article. I'll make corrections and wish to learn something new.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了