Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Django
  • Views
  • Model
  • Template
  • Forms
  • Jinja
  • Python SQLite
  • Flask
  • Json
  • Postman
  • Interview Ques
  • MongoDB
  • Python MongoDB
  • Python Database
  • ReactJS
  • Vue.js
Open In App
Next Article:
Create a ChatBot with OpenAI and Gradio in Python
Next article icon

How To Implement ChatGPT In Django

Last Updated : 22 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Integrating ChatGPT into a Django application allows you to create dynamic and interactive chat interfaces. By following the steps outlined in this article, you can implement ChatGPT in your Django project and provide users with engaging conversational experiences. Experiment with different prompts, improve the user interface and explore further possibilities to enhance the functionality of your chat application.

Implement ChatGPT In Django

Steps to Implement ChatGPT in a Django Application using API

Integrating ChatGPT into a Django web application allows you to build interactive chat interfaces and provide dynamic conversational experiences to users. If you’re looking to master such integrations and explore more advanced projects, theDjango Web Development Course will guide you step-by-step. Let's see the overall steps in summary:

  • Setting up the Django Project.
  • Define a Django view that handles the chat functionality.
  • Configure Django's URL routing to connect the chat view to a specific URL pattern.
  • Designing the User Interface.
  • Testing and Running the Application.

Implement ChatGPT in a Django Application

Basic Setup 

Install Django using pip, and Create a new Django project. Made changes in setting.py, mention your templates folder in TEMPLATES.

Folder Structure

views.py:  Creating the Chat View

The code consists of two functions: query_view and get_completion.

  • query_view is a view function that handles the HTTP requests made to the associated endpoint. When a POST request is received, it extracts the prompt from the request data, calls the get_completion function to generate a completion based on the prompt, and returns the completion as a JSON response. For GET requests, it renders the 'index.html' template.
  • get_completion is a function responsible for generating a completion based on a given prompt using the OpenAI API. It makes a request to the OpenAI API's Completion endpoint, specifying the prompt, maximum tokens, engine, temperature, and other parameters. It retrieves the generated completion from the API response and returns it as the output of the function.
Python
from django.shortcuts import render from django.http import JsonResponse import openai  openai.api_key = 'YOUR_API_KEY'  def get_completion(prompt):     print(prompt)     query = openai.Completion.create(         engine="text-davinci-003",         prompt=prompt,         max_tokens=1024,         n=1,         stop=None,         temperature=0.5,     )      response = query.choices[0].text     print(response)     return response   def query_view(request):     if request.method == 'POST':         prompt = request.POST.get('prompt')         response = get_completion(prompt)         return JsonResponse({'response': response})     return render(request, 'index.html') 

urls.py: Setting up URLs

This code sets up two URL patterns: one for the admin site and another for the root URL, and another which is associated with the query_view function in the views module.

Python
from django.contrib import admin from django.urls import path from . import views   urlpatterns = [     path('admin/', admin.site.urls),     path('', views.query_view, name='query'),  ] 

template/index.py: Creating User Interface

Create an HTML template for the chat interface using HTML, CSS, and Bootstrap, and Set up the necessary JavaScript and AJAX code to handle user interaction.

HTML
<!-- query.html --> <html> <head>     <title>Query</title>     <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>     <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js.cookie.min.js"></script>     <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>     <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css" integrity="sha384-b6lVK+yci+bfDmaY1u0zE8YYJt0TZxLEAFyYSLHId4xoVvsrQu3INevFKo+Xir8e" crossorigin="anonymous">     <script>         $(document).ready(function() {             // Send the form on enter keypress and avoid if shift is pressed             $('#prompt').keypress(function(event) {                 if (event.keyCode === 13 && !event.shiftKey) {                     event.preventDefault();                     $('form').submit();                 }             });             $('form').on('submit', function(event) {                 event.preventDefault();             // get the CSRF token from the cookie             var csrftoken = Cookies.get('csrftoken');                          // set the CSRF token in the AJAX headers             $.ajaxSetup({                 headers: { 'X-CSRFToken': csrftoken }             });                 // Get the prompt                 var prompt = $('#prompt').val();                 var dateTime = new Date();                 var time = dateTime.toLocaleTimeString();                 // Add the prompt to the response div                 $('#response').append('<p>('+ time + ') <i class="bi bi-person"></i>: ' + prompt + '</p>');                 // Clear the prompt                 $('#prompt').val('');                 $.ajax({                     url: '/',                     type: 'POST',                     data: {prompt: prompt},                     dataType: 'json',                     success: function(data) {                         $('#response').append('<p>('+ time + ') <i class="bi bi-robot"></i>: ' + data.response + '</p>');                     }                 });             });         });     </script> </head> <body>     <div class="container p-3">         <h3>ChatGPT Clone</h3>         <div class="mb-3">             <form method="post">                 {% csrf_token %}                 <label for="prompt" class="form-label"><strong>Prompt: </strong></label>                 <textarea class="form-control" type="textarea" id="prompt" name="prompt" rows="3"></textarea>                 <br>                 <button class="btn btn-primary" type="submit">Submit</button>             </form>         </div>         <br>         <div class="mb-3">             <h6>Response:</h6>              <div class="container border overflow-auto h-50" id="response"></div>                      </div>     </div> </body> </html> 

Output:

To learn more about Chat GPT, you can refer to:

  • ChatGPT vs Google BARD

Next Article
Create a ChatBot with OpenAI and Gradio in Python
author
skrg141
Improve
Article Tags :
  • Python
  • Django
  • Python Django
  • ChatGPT
  • AI Chatbot
Practice Tags :
  • python

Similar Reads

  • OpenAI Python API - Complete Guide
    OpenAI is the leading company in the field of AI. With the public release of software like ChatGPT, DALL-E, GPT-3, and Whisper, the company has taken the entire AI industry by storm. Everyone has incorporated ChatGPT to do their work more efficiently and those who failed to do so have lost their job
    15+ min read
  • Extract keywords from text with ChatGPT
    In this article, we will learn how to extract keywords from text with ChatGPT using Python. ChatGPT is developed by OpenAI. It is an extensive language model based on the GPT-3.5 architecture. It is a type of AI chatbot that can take input from users and generate solutions similar to humans. ChatGPT
    4 min read
  • Pandas AI: The Generative AI Python Library
    In the age of AI, many of our tasks have been automated especially after the launch of ChatGPT. One such tool that uses the power of ChatGPT to ease data manipulation task in Python is PandasAI. It leverages the power of ChatGPT to generate Python code and executes it. The output of the generated co
    9 min read
  • Text Manipulation using OpenAI
    Open AI is a leading organization in the field of Artificial Intelligence and Machine Learning, they have provided the developers with state-of-the-art innovations like ChatGPT, WhisperAI, DALL-E, and many more to work on the vast unstructured data available. For text manipulation, OpenAI has compil
    11 min read
  • OpenAI Whisper
    In today's time, data is available in many forms, like tables, images, text, audio, or video. We use this data to gain insights and make predictions for certain events using various machine learning and deep learning techniques. There are many techniques that help us work on tables, images, texts, a
    9 min read
  • Spam Classification using OpenAI
    The majority of people in today's society own a mobile phone, and they all frequently get communications (SMS/email) on their phones. But the key point is that some of the messages you get may be spam, with very few being genuine or important interactions. You may be tricked into providing your pers
    6 min read
  • How to Use chatgpt on Linux
    OpenAI has developed an AI-powered chatbot named `ChatGPT`, which is used by users to have their answers to questions and queries. One can access ChatGPT on searchingness easily. But some users want to access this chatbot on their Linux System. It can be accessed as a Desktop application on Ubuntu o
    6 min read
  • PandasAI Library from OpenAI
    We spend a lot of time editing, cleaning, and analyzing data using various methodologies in today's data-driven environment. Pandas is a well-known Python module that aids with data manipulation. It keeps data in structures known as dataframes and enables you to alter, clean up, or analyze data by c
    9 min read
  • ChatGPT Prompt to get Datasets for Machine Learning
    With the development of machine learning, access to high-quality datasets is becoming increasingly important. Datasets are crucial for assessing the accuracy and effectiveness of the final model, which is a prerequisite for any machine learning project. In this article, we'll learn how to use a Chat
    7 min read
  • How To Implement ChatGPT In Django
    Integrating ChatGPT into a Django application allows you to create dynamic and interactive chat interfaces. By following the steps outlined in this article, you can implement ChatGPT in your Django project and provide users with engaging conversational experiences. Experiment with different prompts,
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences