- Django 2 by Example
- Antonio Melé
- 317字
- 2021-06-25 21:19:07
Installing PostgreSQL
You are currently using SQLite for your blog project. This is sufficient for development purposes. However, for a production environment, you will need a more powerful database, such as PostgreSQL, MySQL, or Oracle. We will change our database to PostgreSQL to benefit from its full-text search features.
If you are using Linux, install dependencies for PostgreSQL to work with Python, like this:
sudo apt-get install libpq-dev python-dev
Then, install PostgreSQL with the following command:
sudo apt-get install postgresql postgresql-contrib
If you are using macOS X or Windows, download PostgreSQL from https://www.postgresql.org/download/ and install it.
You also need to install the Psycopg2 PostgreSQL adapter for Python. Run the following command in the shell to install it:
pip install psycopg2==2.7.4
Let's create a user for our PostgreSQL database. Open the shell and run the following commands:
su postgres
createuser -dP blog
You will be prompted a password for the new user. Enter the desired password and then create the blog database and give the ownership to the blog user you just created with the following command:
createdb -E utf8 -U blog blog
Then, edit the settings.py file of your project and modify the DATABASES setting to make it look as follows:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'blog',
'USER': 'blog',
'PASSWORD': '*****',
}
}
Replace the preceding data with the database name and credentials for the user you created. The new database is empty. Run the following command to apply all database migrations:
python manage.py migrate
Finally, create a superuser with the following command:
python manage.py createsuperuser
You can now run the development server and access the administration site at http://127.0.0.1:8000/admin/ with the new superuser.
Since we switched the database, there are no posts stored in it. Populate your new database with a couple of sample blog posts so that you can perform searches against the database.