Invoking Django methods to connect to a MongoDB database

I have written a service script in my Angular app that adds consumer form info to a local Json-Server database:

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

import { Post } from '../models/post.model';

const httpOptions = {
    headers: new HttpHeaders({
        'Content-Type': 'application/json'
    })
}

@Injectable()
export class DbService {

    consumersApiUrl = "http://localhost:3000/consumers";

    constructor(private httpClient: HttpClient) { }

    addConsumer(post: Post): Observable<Post> {
        return this.httpClient.post<Post>(this.consumersApiUrl, post, httpOptions);
    }
}

This works perfectly…

I have now set up a Django backend and a MongoDB database. In my settings.py file, I have my database connection:

DB_NAME = 'mongodb+srv://User2021:TestPassword@cluster0.j9jz1.mongodb.net/test'

So, I added a new url and a new method to write the info to my database:

@Injectable()
export class DbService {

    consumersApiUrl = "http://localhost:3000/consumers";

    consumersMongodbApiUrl = "http://localhost:8000/consumers/";

    constructor(private httpClient: HttpClient) { }

    addConsumer(post: Post): Observable<Post> {
        return this.httpClient.post<Post>(this.consumersApiUrl, post, httpOptions);
    }

    addConsumerMongodb(post: Post): Observable<Post> {
        return this.httpClient.post<Post>(this.consumersMongodbApiUrl, post, httpOptions);
    }
}

In the MongodbApiUrl, consumers is the name of my database collection.

My first question: Should the link to a real database (whose connection string and name and collection name I know) be like this or should I somehow include the extra info name, etc?


In order to test my database, I have written the following in my views.py which works; meaning I can see the consumer info appearing on my MongoDB Compass:

client = MongoClient(settings.DB_NAME)
db_name = client['myDB']
collection_name = db_name["consumers"]

consumer1 = { ... form info blah blah json object ... }

def add_consumer():
    collection_name.insert_one(consumer1)

I looked at a few examples and realized that the right way to work with Angular and Django is how I started; i.e. service methods to handle database operations, so I wrote this Django method in my views.py file to see my consumer info:

@csrf_exempt
@api_view(['GET', 'POST', 'DELETE'])
def consumer_list(request):
    if request.method == 'GET':
        try:
            print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
            consumers = ConsumerModel.objects.all()
            consumers_serializer = ConsumerModelSerializer(consumers, many=True)

            response = {
                'message': "Got it!",
                'consumers': consumers_serializer.data,
                'error': ""
            }
            return JsonResponse(response, status=status.HTTP_200_OK)
        except:
            error = {
                'message': "Failed!",
                'consumers': "[]",
                'error': "Error"
            }
            return JsonResponse(error, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

and I put the url pattern in my urls.py:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^consumer_list/', consumer_list),
    url(r'^.*', TemplateView.as_view(template_name="home.html"), name="home")

When I log onto http://127.0.0.1:8000/consumer_list/, I see the xxxxx in the console, plus this error:

Internal Server Error: /consumer_list/
"GET /consumer_list/ HTTP/1.1" 500 83

I also get {“message”: “Failed!”, “consumers”: “[]”, “error”: “Error”} on the page, as well as GET http://127.0.0.1:8000/consumer_list/ 500 (Internal Server Error) in the page’s dev console:

enter image description here

My second question: What am I doing wrong here? How do I get my Angular service methods to invoke Django methods to handle database operations? What am I missing here?


p.s. When I run python manage.py migrate in my backend directory, I get the following error, which is strange because if you connect to your MongoDB database via pymongo, you should remove the DATABASES section in your settings.py file which I have done, so I have no idea why I get this:

django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value.

Could someone please help me with this simple example of writing to a database? Been working on it for a week now, to no avail…

Django does not support MongoDB in the ORM directly. You’ve got a couple different options:

  • Use a third-party package such as Djongo to provide ORM access to a MongoDB

  • Access the MongoDB directly in your code and don’t use the ORM.