Evgenii Legotckoi
April 23, 2019, 2:10 p.m.

Django - Tutorial 044. How to Install and Configure Django on Mac OS

I propose to consider the process of installing and configuring a Django project on Mac OS X based on an existing project.

Some steps will be similar to those already performed in the Django setup article for Ubuntu .


Setting up a virtual environment

  1. Intall python 3
    1. brew install python3
  2. Install pip
    1. sudo easy_install pip
  3. Install virtualenv to create virtual environments
    1. sudo pip3 install virtualenv
  4. Setting up a virtual environment for a project
    1. virtualenv project_env --python=python3
  5. Go to the directory of the virtual environment of the project and clone the repository.
    1. cd project_env
    2. git clone git@bitbucket.org:MyUser/project.git
  6. We also clone submodules if your project uses git submodule
    1. cd project
    2. git submodule init
    3. git submodule update
  7. I hope that you are using the requirements.txt file, because the time has come to install all the necessary packages in the project
    1. pip install -r requirements.txt

Install the required version of Python

If you need a specific version of python, for example, if the repositories of your production server do not have the latest version, you need to configure your Mac OS X specifically to work with the required version.

  1. brew install pyenv
  2. echo 'eval "$(pyenv init -)"' >> ~/.bash_profile
  3. source ~/.bash_profile
  4. brew install zlib
  5. pyenv install 3.6.7

If you cannot install python and the following error occurs

  1. BUILD FAILED (OS X 10.14.4 using python-build 20180424)
  2.  
  3. Inspect or clean up the working tree at /var/folders/qk/l3vyb_653ksb55yt5r54rt380000gn/T/python-build.20190421214232.40274
  4. Results logged to /var/folders/qk/l3vyb_653ksb55yt5r54rt380000gn/T/python-build.20190421214232.40274.log
  5.  
  6. Last 10 log lines:
  7. File "/private/var/folders/qk/l3vyb_653ksb55yt5r54rt380000gn/T/python-build.20190421214232.40274/Python-3.6.7/Lib/ensurepip/__main__.py", line 5, in <module>
  8. sys.exit(ensurepip._main())
  9. File "/private/var/folders/qk/l3vyb_653ksb55yt5r54rt380000gn/T/python-build.20190421214232.40274/Python-3.6.7/Lib/ensurepip/__init__.py", line 204, in _main
  10. default_pip=args.default_pip,
  11. File "/private/var/folders/qk/l3vyb_653ksb55yt5r54rt380000gn/T/python-build.20190421214232.40274/Python-3.6.7/Lib/ensurepip/__init__.py", line 117, in _bootstrap
  12. return _run_pip(args + [p[0] for p in _PROJECTS], additional_paths)
  13. File "/private/var/folders/qk/l3vyb_653ksb55yt5r54rt380000gn/T/python-build.20190421214232.40274/Python-3.6.7/Lib/ensurepip/__init__.py", line 27, in _run_pip
  14. import pip._internal
  15. zipimport.ZipImportError: can't decompress data; zlib not available
  16. make: *** [install] Error 1

then create a file .zshrc with the following contents

  1. # For compilers to find zlib you may need to set:
  2. export LDFLAGS="${LDFLAGS} -L/usr/local/opt/zlib/lib"
  3. export CPPFLAGS="${CPPFLAGS} -I/usr/local/opt/zlib/include"
  4.  
  5. # For pkg-config to find zlib you may need to set:
  6. export PKG_CONFIG_PATH="${PKG_CONFIG_PATH} /usr/local/opt/zlib/lib/pkgconfig"

Next, perform the remaining actions.

  1. source .zshrc
  2. pyenv install 3.6.7

Check available versions of python

  1. pyenv versions

Setup the required version of python

  1. pyenv local 3.6.7
  2. pyenv global 3.6.7

Check the version of python that is now used on your Mac OS X.

  1. python --version

After that, you will need to repeat all the steps from the settings of the virtual environment, starting with step 4, if you have already installed virtualenv. Or completely repeat all those steps.

Install and configure PostgreSQL

  1. Uninstalling a previous version of Postgres
    1. brew uninstall --force postgresql
  2. Delete all Postgres files
    1. rm -rf /usr/local/var/postgres
  3. Installing Postgres using Homebrew
    1. brew install postgres
  4. Installing PostGIS using Homebrew
    1. brew install postgis
  5. Start PostgreSQL server. You may need to run this command every time you develop a site.
    1. pg_ctl -D /usr/local/var/postgres start
  6. Creating a project database. Many of these steps were covered in the very first article on setting up Django on a computer running OS
    1. psql postgres
    2. CREATE DATABASE myproject;
    3. CREATE USER myprojectuser WITH PASSWORD 'password';
    4. ALTER ROLE myprojectuser SET client_encoding TO 'utf8';
    5. ALTER ROLE myprojectuser SET default_transaction_isolation TO 'read committed';
    6. ALTER ROLE myprojectuser SET timezone TO 'UTC';
    7. GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser;
    8. \q

Install and configure Nginx

I use Nginx to distribute static content, so we will also install Nginx on the development machine.

  1. brew install nginx
  2. sudo brew services start nginx

Nginx configuration setup

At this step you need to configure the Nginx server. For what you need to edit the nginx.conf file, as well as create the settings file of your server in the servers directory.

  1. nano /usr/local/etc/nginx/nginx.conf

Delete the contents of the file and add the following information..

  1. worker_processes 1;
  2.  
  3. events {
  4. worker_connections 1024;
  5. }
  6.  
  7.  
  8. http {
  9. include mime.types;
  10. default_type application/octet-stream;
  11.  
  12. sendfile on;
  13. keepalive_timeout 65;
  14. include servers/*;
  15. }

Next, create a file myproject

  1. touch /usr/local/etc/nginx/servers/myproject

And add content that will look like this.

  1. server {
  2. listen 80;
  3. server_name 111.222.333.44; # здесь прописать или IP-адрес или доменное имя сервера
  4.  
  5. location /static/ {
  6. root /Users/<user>/myprojectenv/myproject/myproject/;
  7. expires 30d;
  8. }
  9.  
  10. location /media/ {
  11. root /Users/<user>/myprojectenv/myproject/myproject/;
  12. expires 30d;
  13. }
  14.  
  15. location / {
  16. proxy_pass http://127.0.0.1:8000;
  17. proxy_set_header Host $server_name;
  18. proxy_set_header X-Real-IP $remote_addr;
  19. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  20. }
  21. }
  22.  

Then restart the server Nginx

  1. sudo brew services restart nginx

Conclusion

And then we do not forget to complete the migration of the database, the collection of static files through collectstatic and other procedures required in your project.

For Django, I recommend Timeweb VDS-server .

Recommended articles on this topic

By article asked0question(s)

1

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup