How to Install Virtualenv in Ubantu 16.04 or Windows?

Ubantu or Linux

When we are going to run any project in Python Django in the Windows or Ubantu system, we need the virtual environment installed into our system. So first we will see how to install virtual environment into our system.

How to install virtual
virtualenv or environment:

For Ubantu or Linux System:

sudo apt-get install python3-pip

In Windows System, we can use this commands..

apt-get install python3-pip

OR

apt-get install pip

Then install virtualenv using pip3 or pip

For Ubantu System we can use…

sudo pip3 install virtualenv 

OR

sudo pip install virtualenv 

For Windows System, we can use..

pip install virtualenv 


Now create a virtual environment

virtualenv venv 

We can also use a Python interpreter of your choice. like Python 3, Python 3.5 etc

For Ubantu , Linux or Windows we can use this command

virtualenv -p /usr/bin/python2.7 venv

Create virtualenv using Python3

virtualenv -p python3 myenv

Active your virtual environment:

For Ubantu or Linux System..

source venv/bin/activate

Activate Virtual Environment Using fish shell.:

source venv/bin/activate.fish

Activate Virtual Environment using Windows..

Here, the path at venv root path or same directory.

venv/Scripts/activate

Django media files not Loading when DEBUG = FALSE

Django media files not showing with Debug = False on production. It loads without css & media files like images.

This Code is Checked in Django version 2.1

In the url.py file add below code, to import the serve lib

from django.views.static import serve

Add the below codes in urls.py file (in settings.py containing directory)

if not settings.DEBUG:
    urlpatterns += [
        url(r'^uploads/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
        url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),
    ]

Django- Set created & updated date/time in your models

In Django, many of us have question how to create date time in database automatically, When a new data is inserted or Existing Data is Updated.

So, Now we can use to have the date a record was added, or most recently updated. Django makes this really easy.

class Blogs(models.Model):
    title = models.CharField(max_length=100)
    added = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)