Django & React Music Recommendation AI: Tutorial

Updated on Nov 01,2025

This comprehensive tutorial demonstrates how to build a full-stack music recommendation application leveraging the power of Django, React, and Google's Gemini AI. Learn to create an intelligent system that suggests songs based on user queries, providing a unique and engaging musical experience. Whether you're a seasoned developer or just starting, this guide will walk you through each step, from setting up the backend to designing the frontend and integrating AI-driven recommendations. Get ready to dive into the world of AI-powered music!

Key Points

Building a Django backend for handling API requests and database interactions.

Designing a React frontend for user interface and data display.

Integrating Google's Gemini AI for generating music recommendations.

Creating database models to store themes, recommendations, and links.

Parsing JSON responses and saving data to the database.

Setting Up the Django Backend

Understanding Django Models

Django models are Python classes that subclass django.db.models.Model. Each model represents a database table, and each attribute of the model represents a database column. Django provides a rich set of field types to define the data that can be stored in each column. In our Music recommendation project, we define three models: Theme, Recommendation, and Link.

  • Theme: Represents the themes or moods associated with a song. The Theme model has two fields: name (CharField) and description (TextField).
  • Recommendation: Stores the music recommendations generated by the AI. The Recommendation model includes fields like name, artist, album, themes (ManyToManyField), release_date, and album_art.
  • Link: Holds the URLs where the song can be listened to, such as Spotify, Apple Music, and YouTube. The Link model includes fields for recommendation, youtube_link, spotify_link, and apple_music_link. These models will help to structure data and create an orgenized database for our project.

Creating API Endpoints with Django REST Framework

Django REST Framework (DRF) is a powerful and flexible toolkit for building Web APIs. DRF makes it easy to serialize data, handle authentication, and create browsable APIs.

To create API endpoints for our music recommendation app, we'll use DRF's APIView class and define methods for handling HTTP requests.

Here's how we create the MusicRecommendationAIView:

  1. Import necessary modules and set up the API key for Google's Gemini AI.
  2. Define the post method to handle incoming POST requests. This method retrieves the user query from the request data.
  3. Use Google's Gemini AI to generate music recommendations based on the user query.
  4. Parse the JSON response from the AI and save the data to the database.
  5. Return a JSON response indicating the status of the request.

Integrating Google's Gemini AI

Configuring the Gemini AI API

Google's Gemini AI provides powerful capabilities for generating creative and informative text. In our music recommendation app, we use Gemini AI to suggest songs based on user queries.

To integrate Gemini AI, you'll need to:

  1. Obtain an API key from Google AI Studio.
  2. Configure the Gemini AI model using the genai.configure method.
  3. Use the genai.GenerativeModel to generate content based on a Prompt.

The prompt includes instructions for the AI to act as a music recommendation assistant, specify the desired format for the response (JSON), and list the attributes to include for each song (name, artist, album, themes, release date, album art, and links). Ensure that you provide clear and concise instructions to get the best results from the AI.

By using Gemini AI, our music recommendation app can dynamically generate personalized song suggestions, making the user experience more engaging and tailored to their preferences.

Crafting Effective Prompts for Music Recommendations

Crafting effective prompts is essential to getting high-quality music recommendations from Gemini AI. The prompt should clearly instruct the AI to act as a music recommendation assistant and specify the format for the response.

In our project, the prompt includes the following instructions:

  • Act as a music recommendation assistant.
  • Recommend five songs that fit the user's query.
  • Provide the song's name, artist, album, themes, release date, album art, and links.
  • Return the response in JSON format.

Here's an example of a well-crafted prompt:


Instructions: You are a music recommendation assistant. Based on the user query, your task is to recommend 5 songs that fit the query and performing the song.
name: Title of the song.
artist: The main artist or band performing the song.
album: The album the song belongs to.
release date: The song's release date in YYYY-MM-DD format.
themes: A list of themes or moods the song conveys (e.g., love, nostalgia, empowerment, sadness).
album_art: URL to the album cover image.
links: An array containing URLs where the song can be listened to (e.g., Spotify, Apple Music, YouTube).
Please don't include  json  in the result. Just provide the object.```
By providing clear and specific instructions, you can guide the AI to generate accurate and relevant music recommendations that enhance the user experience.

Step-by-Step Guide: Building the Music Recommendation App

Step 1: Setting Up the Django Project

First, create a new Django project and app. Navigate to your desired project directory and run the following commands:

django-admin startproject music_recommender
cd music_recommender
python manage.py startapp music

This will create a new Django project named music_recommender and an app named music.

Step 2: Defining the Models

In the music app, define the models in models.py to represent themes, recommendations, and links. Here's an example of how to define the models:

from django.db import models

class Theme(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()

    def __str__(self):
        return self.name

class Recommendation(models.Model):
    name = models.CharField(max_length=100)
    artist = models.CharField(max_length=100)
    album = models.CharField(max_length=100)
    themes = models.ManyToManyField(Theme, null=True, blank=True)
    release_date = models.CharField(max_length=100)
    album_art = models.URLField(max_length=500)

    def __str__(self):
        return self.name

class Link(models.Model):
    recommendation = models.ForeignKey(Recommendation, on_delete=models.CASCADE)
    youtube_link = models.URLField(max_length=500)
    spotify_link = models.URLField(max_length=500)
    apple_music_link = models.URLField(max_length=500)

    def __str__(self):
        return self.recommendation.name

Remember to run migrations after defining the models to create the corresponding database tables.

Step 3: Creating API Views

Use Django REST Framework to create API views for handling requests and generating music recommendations.

In views.py, define the MusicRecommendationAIView as follows:

import genai
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Theme, Recommendation, Link
import json
from rest_framework import status

genai.configure(api_key=settings.GEMINI_API_KEY)

class MusicRecommendationAIView(APIView):
    def post(self, request):
        user_query = request.data.get('query', '')
        prompt = f"""You are a music recommendation assistant. Based on the user query, your task is to recommend 5 songs that fit the query and performing the song.
name: Title of the song.
artist: The main artist or band performing the song.
album: The album the song belongs to.
release date: The song's release date in YYYY-MM-DD format.
themes: A list of themes or moods the song conveys (e.g., love, nostalgia, empowerment, sadness).
album_art: URL to the album cover image.
links: An array containing URLs where the song can be listened to (e.g., Spotify, Apple Music, YouTube).
Please don't include  json  in the result. Just provide the object."""

        model = genai.GenerativeModel('gemini-1.5-flash')
        response = model.generate_content(prompt)
        json_response = None

        try:
            json_response = json.loads(response.text)
        except json.JSONDecodeError as e:
            print(f"Failed to decode JSON: {e}")
            return Response({"error": "Failed to decode JSON"}, status=status.HTTP_400_BAD_REQUEST)

        def save_recommendations_from_json(json_response):
            recommendations = json_response.get('response', [])

            for rec in recommendations:
                theme_objects = []
                for theme in rec.get('themes'):
                    theme_obj, created = Theme.objects.get_or_create(name=theme)
                    theme_objects.append(theme_obj)

                recommendation = Recommendation.objects.create(
                    name=rec.get('name'),
                    artist=rec.get('artist'),
                    album=rec.get('album'),
                    release_date=rec.get('release_date'),
                    album_art=rec.get('album_art'),
                )

                recommendation.themes.set(theme_objects)

                Link.objects.create(
                    recommendation=recommendation,
                    youtube_link=rec.get('links')[0],
                    spotify_link=rec.get('links')[1],
                    apple_music_link=rec.get('links')[2]
                )

        save_recommendations_from_json(json_response)
        return Response({"response": response.status}, status=status.HTTP_200_OK)

Pricing for the Tech Stack

Understanding the Costs

When building a music recommendation AI with Django, React, and Gemini AI, it's essential to understand the pricing implications of each component. While Django and React are open-source frameworks and free to use, integrating Gemini AI and hosting the application will incur costs.

Here’s a breakdown of the potential costs involved:

  • Django & React: These are free, open-source tools. No licensing fees are involved.
  • Gemini AI API: Google AI’s pricing varies based on usage. You might get free credits initially, but you will need to monitor usage to avoid unexpected charges.
  • Hosting: This depends on the cloud provider (e.g., AWS, Google Cloud, Azure) and the resources you use. Costs may include server rental, database usage, and bandwidth. For example, the basic droplet on digital Ocean would cost about $6 a month.
  • Domain Name: This may cost $10-$20 per year for registering the domain name.

Before launching, always review the pricing details of your chosen cloud services and APIs to avoid unforeseen costs and ensure you stay within your budget.

Advantages and Disadvantages of Using Django, React, and Gemini AI

👍 Pros

Rapid Development: Django's high-level framework and React's component-based architecture enable faster development.

Scalability: Both Django and React are highly scalable, making them suitable for projects of any size.

AI-Powered Recommendations: Gemini AI provides personalized and accurate music suggestions.

User-Friendly Interface: React allows for creating interactive and engaging user interfaces.

Large Community Support: Django and React have large and active communities, offering ample resources and support.

👎 Cons

Complexity: Integrating AI models can add complexity to the project.

Cost: Using AI services may incur costs based on usage.

Dependency: Reliance on external APIs (like Gemini AI) can introduce dependency risks.

Learning Curve: Requires familiarity with Django, React, and AI concepts.

Core Features of the Music Recommendation AI

Key Functionalities

Our music recommendation AI boasts several core features that make it a valuable tool for music enthusiasts.

These features include:

  • AI-Powered Recommendations: Leverages Gemini AI to provide personalized music suggestions based on user queries.
  • Database Storage: Utilizes Django models to store and manage music data, themes, and links.
  • API Endpoints: Django REST Framework provides API endpoints for handling requests and responses.
  • Frontend Interface: A React-based user interface for seamless interaction and data display.
  • JSON Parsing: Efficiently parses JSON responses from the AI to extract and store relevant information.

These features combined deliver a robust and user-friendly music recommendation experience.

Use Cases for the Music Recommendation AI

Real-World Applications

The music recommendation AI can be applied in various scenarios to enhance user experience and engagement.

Here are a few key use cases:

  • Music Streaming Platforms: Enhance personalized playlists and song suggestions.
  • Social Media Apps: Recommend songs based on user posts and preferences.
  • Event Planning: Suggest music for parties and gatherings based on event themes.
  • Educational Purposes: Assist students in exploring different genres and artists.
  • Fitness Apps: Create motivating workout playlists based on user preferences.
  • Mood-Based Music: Suggest music to improve someone's mood.

Frequently Asked Questions

What is Django REST Framework?
Django REST Framework is a powerful and flexible toolkit for building Web APIs. It provides tools for serializing data, handling authentication, and creating browsable APIs. It simplifies the process of creating RESTful APIs with Django. Django is an open source web application framework.
How does the music recommendation AI work?
The music recommendation AI works by leveraging Google's Gemini AI to generate music suggestions based on user queries. When a user enters a query, the backend sends it to Gemini AI, which returns a JSON response containing song recommendations. The backend then parses this response and saves the data to the database.
What are Django models?
Django models are Python classes that define the structure of your database tables. Each model represents a table, and each attribute of the model represents a column in the table. Django models provide a convenient way to interact with the database using Python code.

Related Questions

How to improve Gemini AI prompt?
I'll provide general recommendations. For the best and most relevant search results, I recommend you provide as much detail as possible. Be concise and to the point. Also remember, the structure of your prompt will impact the quality of response you get back. If this doesn't work, you may consider a different LLM.
What cloud technologies are good for hosting?
The best cloud technologies for hosting can vary based on your specific needs and budget, but here are a few general recommendations. For simple hobby projects, Digital Ocean provides a variety of options. For Enterprise level applications, you may consider AWS, Azure, and Google Cloud Platform.

Most people like