Support Online
Skip to main content

Connecting Django Application to MongoDB Database with PyMongo

In this guide, you will connect your Django project to MongoDB using PyMongo, configure the connection securely, and perform data operations on MongoDB.

1. Managed MongoDB Cluster Preparation (GenixNode Instance)

1.1 Creating a MongoDB Cluster

Create a new Managed MongoDB Cluster by logging into the GenixNode Administration Panel. Determine your dataset and connection parameters.

1.2 Identifying Trusted Sources

For MongoDB security, add the IP address of the server on which your application runs to the "Trusted Sources" section in the management panel. This will only accept connections from the IPs you specify.

1.3 Storing Connection Information

Once the MongoDB cluster is created, download the Connection String and CA Certificate. Keep this information in a safe place.

1.4 Resetting Admin Password

Increase security by resetting the admin password from the Users tab.


2. Django Project and PyMongo Installation

2.1 Starting the Django Project

Create a new project directory and start Django:

mkdir ~/genixnode-mongo-test
cd ~/genixnode-mongo-test
django-admin startproject DjangoNoSQL

2.2 Starting the Django Application

Create the application directory and launch the application with the name rabisuapp:


cd DjangoNoSQL
python3 manage.py startapp rabisuapp

2.3 Installing Required Libraries

Install PyMongo and DNS resolver Dnspython libraries for MongoDB connection:


pip3 install pymongo dnspython

3. Configuring Django Settings

3.1 Editing the settings.py File

Disable Django's default database and configure the connection with MongoDB.


nano DjangoNoSQL/settings.py

Disable the DATABASES section by commenting it like this:


DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}

Add your app to the INSTALLED_APPS list:


INSTALLED_APPS = [
'rabisuapp',
'django.contrib.admin',
# ... diğer bileşenler
]

4. Setting Up PyMongo Connection and Data Transaction

4.1 Defining URL Configuration

Open urls.py and point the main path (/) of your Django project to rabisuapp.


from django.urls import path, include

urlpatterns = [
path('', include('rabisuapp.urls')), # GenixNode uygulamasının URL'lerini dahil eder
path('admin/', admin.site.urls),
]

4.2 Defining Application URLs

Create the file rabisuapp/urls.py and add the following URL redirect:


from django.urls import path
from . import views

urlpatterns = [
path('', views.index, name='index'), # Ana sayfa görünümünü index'e yönlendirir
]

4.3 Using PyMongo for CRUD Operation

Open views.py to establish the connection with MongoDB and perform simple data operations.


from django.http import HttpResponse
import pymongo # PyMongo kütüphanesini içeri aktarır
import os # CA sertifikası yolu için gerekli olabilir

def index(request):
# Bağlantı dizesi ve sertifika yolunuzu kendi bilgilerinizle değiştirin
CONN_STR = 'mongodb+srv://admin_user:guclu_parola@TR1-cluster.rabisucloud.net/admin?authSource=admin&tls=true&tlsCAFile=/home/genixnode/mongodb-ca.crt'

try:
# MongoDB istemcisini başlatır
client = pymongo.MongoClient(CONN_STR)
dbname = client['genixnode_db'] # Veritabanı adını tanımlar
collection = dbname['genixnode_mascot'] # Koleksiyon adını tanımlar

# Yeni bir belge (document) oluşturur ve ekler
yeni_belge = {"ad": "GenixNode", "tip": "Bulut"}
collection.insert_one(yeni_belge)

# Veriyi çeker ve terminalde yazdırır
cekilen_veriler = collection.find({})
sonuc = [f"Belge eklendi ve çekildi: {r['ad']} - {r['tip']}" for r in cekilen_veriler]

return HttpResponse(f"<h1>MongoDB Bağlantısı Başarılı!</h1><p>{'<br>'.join(sonuc)}</p>")

except Exception as e:
return HttpResponse(f"<h1>Bağlantı Hatası!</h1><p>&#123;e&#125;</p>")


5. Testing the App

5.1 Starting the Server

Start the server and verify that the connection is successful.


python3 manage.py runserver

5.2 Viewing Result

Go to http://127.0.0.1:8000 in your browser. "MongoDB Connection Successful!" appears on the screen. You should see the message.


Frequently Asked Questions (FAQ)

  1. Why do we use PyMongo instead of Django ORM?

Django ORM is designed for relational databases. Using PyMongo for NoSQL databases such as MongoDB allows you to use the flexible structure of the database more efficiently.

  1. What does the client = pymongo.MongoClient() command do?

This command allows you to connect to the MongoDB database. The connection string contains all the necessary information about the MongoDB cluster.

  1. What does CA Certificate do?

CA Certificate provides secure communication with your MongoDB database by establishing secure SSL/TLS connections.

  1. Why should I use PyMongo?

PyMongo allows you to easily exchange data between MongoDB and Python applications and provides tools for all MongoDB-related CRUD operations.


Result

In this guide, you learned how to use PyMongo to connect your Django application to MongoDB. You can make database management more efficient by learning about adding, querying and connecting data with MongoDB. You can try this setup now on GenixNode's powerful and reliable Virtual Server Instances.