Last Updated : 23 Jul, 2025
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.
Steps to Implement ChatGPT in a Django Application using APIIntegrating 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:
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 ViewThe code consists of two functions: query_view and get_completion.
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/js-cookie@3.0.0/dist/js.cookie.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.2/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:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4