Rapid AI: Powered Applications With the Django-MongoDB Backend and…

This article is written by Marko Aleksendric (Data Analyst) If you've got an appetite for learning about the latest in AI and how you can use it to transform the way you work, then this article is for you.

This article is written by Marko Aleksendric (Data Analyst)

If you’ve got an appetite for learning about the latest in AI and how you can use it to transform the way you work, then this article is for you. Discover how the powerful combination of Django, MongoDB’s new AI smarts, and Voyage AI can turn your leftover ingredients into delicious dinner ideas – no grocery run needed!

MongoDB is enhancing its platform with AI-powered search and retrieval features, like embeddings and reranking, to make data processing smarter and more efficient. These tools are key in systems like retrieval-augmented generation (RAG), which improve AI outputs by fetching the most relevant data to ground those responses. By integrating these capabilities directly into the database layer, MongoDB is simplifying application stacks, reducing the need for complex AI pipelines, and improving data accuracy. In this project, we’ll build a RAG-like system to demonstrate how these features work in practice!

A Brief History

Django is one of the most mature and actively maintained web frameworks in the Python ecosystem, renowned for its “batteries included” philosophy. It enables rapid development of secure, maintainable web applications by offering built-in support for URL routing, middleware, template rendering, form handling, authentication, and database abstraction via a powerful Object-Relational Mapper (ORM). Django projects follow the Model–View–Template (MVT) architecture, where models define the data schema, views handle the application logic, and templates control the presentation layer.

Though initially designed to render HTML on the server side, Django has evolved to support modern web development patterns. Tools like Django REST Framework and Django-Ninja allow developers to expose APIs in JSON format, enabling Django to serve as a backend for single-page applications and mobile apps. In addition, its extensible admin interface—automatically generated from your models—provides powerful CRUD capabilities out of the box. Combined with robust security defaults, scalability features, a vast third-party package ecosystem, and thorough documentation, Django remains a top choice for Python developers building anything from simple websites to enterprise-grade applications.

Learn more in-depth about the history here!

A Needed Integration

The Django MongoDB Backend is a new official integration from MongoDB that lets Django developers use MongoDB as the database behind their projects. This backend offers deep support for core Django features like models, migrations, and the admin panel—while still giving access to MongoDB’s advanced capabilities like aggregations and vector search. It’s easy to set up using Django’s standard settings system, and while it’s still in public preview and not yet recommended for production, it opens up exciting possibilities for building modern, AI-powered web apps with Django and MongoDB together!

The Project: A Smart Recipe Application

We’ll use Django and MongoDB to cook up a smart recipe app that finds dishes you can make with what’s already in your fridge. In this project, you’ll work with several cutting-edge technologies to build an AI-powered recipe app. Here’s a quick rundown of what you’ll be using and learning:

– Django for creating the web application
Django MongoDB Backend to integrate MongoDB seamlessly
– PyMongo for direct interaction with MongoDB
– Voyage AI for generating embeddings of recipe ingredients
– Claude LLM by Anthropic for smart recipe suggestions

Prerequisites

Before diving in, make sure you have these resources ready:

– IDE: Visual Studio Code
– Python 3.10 or later (we’ll use 3.12.6)
– Docker for containerization
Django MongoDB Backend installed
– MongoDB Atlas account for database hosting
– Voyage AI account for embeddings
– Claude LLM account for recipe suggestions

Setting Up the Environment

Installing Dependencies

First, let’s create a virtual environment and install the necessary dependencies. Open your terminal and run:

“`bash
python -m venv venv
source venv/bin/activate # On Windows use `venv\Scripts\activate`
pip install django djangorestframework pymongo django-mongodb-engine
“`

Configuring Django

Create a new Django project and navigate into it:

“`bash
django-admin startproject smartrecipe
cd smartrecipe
“`

Update your `settings.py` to use MongoDB as the database backend:

“`python
DATABASES = {
‘default’: {
‘ENGINE’: ‘djongo’,
‘NAME’: ‘smartrecipe’,
‘CLIENT’: {
‘host’: ‘your_mongodb_atlas_connection_string’
}
}
}
“`

Building the Application

Creating Models

Define your models in `models.py`. For this project, we’ll create models for `Ingredient` and `Recipe`.

“`python
from django.db import models

class Ingredient(models.Model):
name = models.CharField(max_length=100)

def str(self):
return self.name

class Recipe(models.Model):
title = models.CharField(max_length=200)
ingredients = models.ManyToManyField(Ingredient)
instructions = models.TextField()

def str(self):
return self.title
“`

Setting Up Views and URLs

Create views to handle the application logic and set up URLs to route requests. In `views.py`:

“`python
from django.shortcuts import render
from .models import Recipe, Ingredient

def home(request):
return render(request, ‘home.html’)

def suggest_recipes(request):

Logic to suggest recipes based on available ingredients

pass
“`

In `urls.py`:

“`python
from django.urls import path
from . import views

urlpatterns = [
path(”, views.home, name=’home’),
path(‘suggest/’, views.suggest_recipes, name=’suggest_recipes’),
]
“`

Integrating Voyage AI

To generate embeddings of recipe ingredients, integrate Voyage AI. Create a new file `ai_utils.py`:

“`python
import voyage

def get_ingredient_embeddings(ingredients):
api_key = ‘your_voyage_api_key’
client = voyage.Client(api_key)
embeddings = client.get_embeddings(ingredients)
return embeddings
“`

Using Claude LLM for Recipe Suggestions

Integrate Claude LLM to provide smart recipe suggestions. In `ai_utils.py`:

“`python
import anthropic

def get_recipe_suggestions(embeddings):
api_key = ‘your_claude_api_key’
client = anthropic.Client(api_key)
suggestions = client.get_suggestions(embeddings)
return suggestions
“`

Putting It All Together

Creating the Home Page

Design the home page to allow users to input their ingredients. In `templates/home.html`:

“`html



Smart Recipe App

Welcome to the Smart Recipe App

{% csrf_token %}





“`

Implementing the Suggest Recipes Logic

In `views.py`, implement the logic to suggest recipes based on user input:

“`python
from django.shortcuts import render
from .models import Recipe, Ingredient
from .ai_utils import get_ingredient_embeddings, get_recipe_suggestions

def suggest_recipes(request):
if request.method == ‘POST’:
ingredients_input = request.POST[‘ingredients’]
ingredients_list = ingredients_input.split(‘,’)
embeddings = get_ingredient_embeddings(ingredients_list)
suggestions = get_recipe_suggestions(embeddings)

Fetch recipes from the database based on suggestions

recipes = Recipe.objects.filter(title__in=suggestions)

return render(request, ‘suggestions.html’, {‘recipes’: recipes})
“`

Displaying Recipe Suggestions

Create a template to display the suggested recipes. In `templates/suggestions.html`:

“`html



Recipe Suggestions

Your Recipe Suggestions

    {% for recipe in recipes %}

  • {{ recipe.title }}

    Ingredients: {{ recipe.ingredients.all|join:”, ” }}

    Instructions: {{ recipe.instructions }}

  • {% endfor %}



“`

Conclusion

Congratulations! You’ve built a smart recipe application using Django, MongoDB, Voyage AI, and Claude LLM. This project demonstrates how AI can enhance traditional web applications, making them more intelligent and user-friendly. As MongoDB continues to evolve its AI capabilities, the possibilities for integrating AI into web applications will only grow.

FAQ

What is the Django MongoDB Backend?

The Django MongoDB Backend is an official integration from MongoDB that allows Django developers to use MongoDB as their database. It supports core Django features like models, migrations, and the admin panel while providing access to MongoDB’s advanced capabilities.

Can I use this project for production?

While the Django MongoDB Backend is in public preview, it is not yet recommended for production use. However, this project can serve as a great learning experience and a foundation for future developments.

What are the benefits of using AI in web applications?

Using AI in web applications can enhance user experience by providing personalized recommendations, improving search functionality, and automating tasks. It can also lead to more efficient data processing and better decision-making.

How can I integrate other AI models into this project?

You can integrate other AI models by following a similar approach. Create utility functions to interact with the AI models’ APIs, and use these functions in your Django views to process data and generate responses.

What are the prerequisites for this project?

The prerequisites include an IDE like Visual Studio Code, Python 3.10 or later, Docker for containerization, a MongoDB Atlas account, and accounts for Voyage AI and Claude LLM. Ensure you have these resources ready before diving into the project.

By following this tutorial, you’ll gain valuable insights into how to build modern, AI-powered web applications using Django and MongoDB. Happy coding!

More Reading

Post navigation

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

If you like this post you might also like these

back to top