Evgenii Legotckoi
Evgenii LegotckoiApril 23, 2019, 4:10 a.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
    brew install python3
  2. Install pip
    sudo easy_install pip
  3. Install virtualenv to create virtual environments
    sudo pip3 install virtualenv
  4. Setting up a virtual environment for a project
    virtualenv project_env --python=python3
  5. Go to the directory of the virtual environment of the project and clone the repository.
    cd project_env
      git clone git@bitbucket.org:MyUser/project.git
  6. We also clone submodules if your project uses git submodule
    cd project
      git submodule init
      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
    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.

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

If you cannot install python and the following error occurs

BUILD FAILED (OS X 10.14.4 using python-build 20180424)

Inspect or clean up the working tree at /var/folders/qk/l3vyb_653ksb55yt5r54rt380000gn/T/python-build.20190421214232.40274
Results logged to /var/folders/qk/l3vyb_653ksb55yt5r54rt380000gn/T/python-build.20190421214232.40274.log

Last 10 log lines:
  File "/private/var/folders/qk/l3vyb_653ksb55yt5r54rt380000gn/T/python-build.20190421214232.40274/Python-3.6.7/Lib/ensurepip/__main__.py", line 5, in <module>
    sys.exit(ensurepip._main())
  File "/private/var/folders/qk/l3vyb_653ksb55yt5r54rt380000gn/T/python-build.20190421214232.40274/Python-3.6.7/Lib/ensurepip/__init__.py", line 204, in _main
    default_pip=args.default_pip,
  File "/private/var/folders/qk/l3vyb_653ksb55yt5r54rt380000gn/T/python-build.20190421214232.40274/Python-3.6.7/Lib/ensurepip/__init__.py", line 117, in _bootstrap
    return _run_pip(args + [p[0] for p in _PROJECTS], additional_paths)
  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
    import pip._internal
zipimport.ZipImportError: can't decompress data; zlib not available
make: *** [install] Error 1

then create a file .zshrc with the following contents

# For compilers to find zlib you may need to set:
export LDFLAGS="${LDFLAGS} -L/usr/local/opt/zlib/lib"
export CPPFLAGS="${CPPFLAGS} -I/usr/local/opt/zlib/include"

# For pkg-config to find zlib you may need to set:
export PKG_CONFIG_PATH="${PKG_CONFIG_PATH} /usr/local/opt/zlib/lib/pkgconfig"

Next, perform the remaining actions.

source .zshrc
pyenv install 3.6.7

Check available versions of python

pyenv versions

Setup the required version of python

pyenv local 3.6.7
pyenv global 3.6.7

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

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
    brew uninstall --force postgresql
  2. Delete all Postgres files
    rm -rf /usr/local/var/postgres
  3. Installing Postgres using Homebrew
    brew install postgres
  4. Installing PostGIS using Homebrew
    brew install postgis
  5. Start PostgreSQL server. You may need to run this command every time you develop a site.
    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
    psql postgres
      CREATE DATABASE myproject;
      CREATE USER myprojectuser WITH PASSWORD 'password';
      ALTER ROLE myprojectuser SET client_encoding TO 'utf8';
      ALTER ROLE myprojectuser SET default_transaction_isolation TO 'read committed';
      ALTER ROLE myprojectuser SET timezone TO 'UTC';
      GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser;
      \q

Install and configure Nginx

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

brew install nginx
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.

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

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

worker_processes  1;

events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    keepalive_timeout  65;
    include servers/*;
}

Next, create a file myproject

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

And add content that will look like this.

server {
    listen 80;
    server_name 111.222.333.44; # здесь прописать или IP-адрес или доменное имя сервера

    location /static/ {
        root /Users/<user>/myprojectenv/myproject/myproject/;
        expires 30d;
    }

    location /media/ {
        root /Users/<user>/myprojectenv/myproject/myproject/;
        expires 30d;
    }

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $server_name;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Then restart the server Nginx

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 .

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
МВ

Qt - Test 001. Signals and slots

  • Result:68points,
  • Rating points-1
ЛС

C++ - Test 001. The first program and data types

  • Result:53points,
  • Rating points-4
АА

C++ - Test 001. The first program and data types

  • Result:60points,
  • Rating points-1
Last comments
ИМ
Игорь МаксимовOct. 5, 2024, 7:51 a.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 11:02 a.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 10:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
Now discuss on the forum
K
KeithfapOct. 13, 2024, 9:24 a.m.
добавить qlineseries в функции North Symbol by Bubnov Ltd https://seven-elephants.com/en/categories/penthouse/ Искеле – жемчужина острова! Все факторы говорят про большой инвестиционный потенциал данного района как для …
JW
Jhon WickOct. 1, 2024, 3:52 p.m.
Indian Food Restaurant In Columbus OH| Layla’s Kitchen Indian Restaurant If you're looking for a truly authentic https://www.laylaskitchenrestaurantohio.com/ , Layla’s Kitchen Indian Restaurant is your go-to destination. Located at 6152 Cleveland Ave, Colu…
КГ
Кирилл ГусаревSept. 27, 2024, 9:09 a.m.
Не запускается программа на Qt: точка входа в процедуру не найдена в библиотеке DLL Написал программу на C++ Qt в Qt Creator, сбилдил Release с помощью MinGW 64-bit, бинарнику напихал dll-ки с помощью windeployqt.exe. При попытке запуска моей сбилженной программы выдаёт три оши…
F
FynjyJuly 22, 2024, 4:15 a.m.
при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …

Follow us in social networks