Python Tips
My python tips with Django and Virtual Environment
Virtual Environment
A virtualenv allows you to modularize and run your python code without breaking the codebase of another app when upgrading a python module installed globally.
Any module you install in your virtual environment, will stay inside that virtual environment.
Never commit the venv/
dir to your source control (git). Only commit the requirements.txt
file, which you can always generate using:pip freeze > requirements.txt
inside our environment. This will allow for any user to create the venv/
himself, and install the required modules for the project in that venv based on our file using pip install -r requirements.txt
.
- Install virtualenv:
pip3 install virtualenv
- Create a virtual env (preferably for each project — in the root dir of the same project):
python3 -m virtualenv <new_environment_name>
(preferably usevenv
for the name) - And now whenever you are working with your project, activate your virtual environment using:
source venv/bin/activate
– This will allow us to simply usepython or pip
instead ofpython3 or pip3
, because our environment uses the same version of python we used to create the environment ;) - To deactivate/exit an environment simply run
deactivate
.
Django
To run custom scripts either use this guide (Quick and Dirty — 2nd link) or write a custom django-admin command (Recommended — 1st Link).
Note that i'm not using
python3
norpip3
because i'm assuming that we are in an activated venv (See above for instructions on virtualenv).
- Install Django in your venv:
pip install django
- Django basically consists of 1 project, many applications.
E.g: Project: Google— Apps: search, images, etc… - To create a project use:
django-admin startproject <projectname>
- To create an application, navigate to the project dir and use:
python manage.py startapp <appname>
and install the app by navigating to<projectname>/<projectname>/settings.py
and adding the<appname>
into theINSTALLED_APPS
array.
* For every new application, you may want to create a new<appname>/urls.py
file and include that inside tha main<projectname>/urls.py
:
urlpatterns = [
path("", include("<appname>.urls")
]
- To start the web server use:
python manage.py runserver