Django Python Razorpay Payment Gateway Integration Example

Published On: 02/07/2022 | Category: Django Python

Hi Dev,

This article goes in detailed on razorpay payment gateway integration with python django. we will help you to give example of razorpay payment gateway integration with django app. This post will give you simple example of razorpay payment gateway integration with django developer. you'll learn razorpay payment gateway integration with python django database. Let's see bellow example razorpay payment gateway integration with django example.

Razorpay is very simple, hassle free and easy to integrate payment gateway.Razorpay is one of the popular payment gateway, that allows us to accept payment from your customer.

Here i explained simply step by step let's see bellow example razorpay payment gateway integration with django example.

Step 1 : Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2 : Create a App
python3 startapp payment
Step 3 : Update

In this step we require to do two things in our file, One is to change the path of template look up directory. Second one is to configure our media folder. Add the below lines to your file:

So, in this exmaple we will use bootstrap 4 crispy forms Crispy Bootstrap Template Pack so if you have not installed so you can follow this article will help you..

Next, you need to add it in the file as follows:

Step 4 : Database Setup

Next step, we will modify the file and update the database settings to configure the mydb database:
    'default': {  
        'ENGINE': 'django.db.backends.mysql',  
        'NAME': 'example',  
Step 5: Create Razorpay Account

First you need to create account on razorpay. then you can easily get account key id and key secret.

Create Account from here:

After register successfully. you need to go bellow link and get id and secret as bellow screen shot:

Go Here:

Next you can get account key id and secret and add on file as like bellow:
Step 6: Install Razorpay Library

In this step, we need to install razorpay package to use razorpay api. so let's run bellow command:

pip install razorpay
Step 7: Create a Model

In this step we will require the database model for storing contacts.Open the payment/ file and add the following code:

from django.db import models

class Order(models.Model):
    name = models.CharField(max_length=100)
    amount = models.CharField(max_length=100)
    order_id = models.CharField(max_length=100, blank=True)
    razorpay_payment_id = models.CharField(max_length=100, blank=True)
    paid = models.BooleanField(default=False)
Step 8: Create a FormClass

In this step we will require the create a formclass for some adding bootstrap class and add button.Open the payment/ file and add the following code:

from django import forms
from .models import Order
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit

class OrderForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = "__all__"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.layout = Layout(
            Submit('submit', 'Buy', css_class='button white btn-block btn-primary')

After creating these model, you need to create migrations using the following command:

Step 9 : Create a Migrations
python makemigrations

After successfully run the above command go to the payment/migrations/

# Generated by Django 4.0.5 on 2022-07-01 06:10

from django.db import migrations, models

class Migration(migrations.Migration):

    initial = True

    dependencies = [

    operations = [
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=100)),
                ('amount', models.CharField(max_length=100)),
                ('order_id', models.CharField(blank=True, max_length=100)),
                ('razorpay_payment_id', models.CharField(blank=True, max_length=100)),
                ('paid', models.BooleanField(default=False)),

Next, you need to migrate your database using the following command:

python migrate
Step 10 : Creating the Views

In this step, we need to create the views for performing fetch record to the database.Open the payment/ file and add:

from django.shortcuts import render
from .forms import OrderForm
import razorpay
from .models import Order
from django.conf import settings

def payment(request):
    if request.method == "POST":
        name = request.POST.get('name')
        amount = int(request.POST.get('amount')) * 100

        # create Razorpay client
        client = razorpay.Client(auth=(settings.RAZORPAY_KEY_ID, settings.RAZORPAY_KEY_SECRET))

        # create order
        response_payment = client.order.create(dict(amount=amount,

        order_id = response_payment['id']
        order_status = response_payment['status']

        if order_status == 'created':
            order = Order(
            response_payment['name'] = name

            form = OrderForm(request.POST or None)
            return render(request, 'payment.html', {'form': form, 'payment': response_payment})

    form = OrderForm()
    return render(request, 'payment.html', {'form': form})

def payment_status(request):
    response = request.POST
    params_dict = {
        'razorpay_order_id': response['razorpay_order_id'],
        'razorpay_payment_id': response['razorpay_payment_id'],
        'razorpay_signature': response['razorpay_signature']

    # client instance
    client = razorpay.Client(auth=(settings.RAZORPAY_KEY_ID, settings.RAZORPAY_KEY_SECRET))

        status = client.utility.verify_payment_signature(params_dict)
        order = Order.objects.get(order_id=response['razorpay_order_id'])
        order.razorpay_payment_id = response['razorpay_payment_id']
        order.paid = True
        return render(request, 'callback.html', {'status': True})
        return render(request, 'callback.html', {'status': False})
Step 11 : Creating the Templates

Next, open the payment/templates/base.html file and the add:

{% load static %}
<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>Tuts-Stations Member</title>
    <link rel="stylesheet" href="[email protected]/dist/css/bootstrap.min.css">
    <script src=""></script>
    <script src="[email protected]/dist/umd/popper.min.js"
    <script src="[email protected]/dist/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="{% static 'css/font-awesome-4.7.0/css/font-awesome.min.css' %}">
    <style type="text/css">
        .success-animation {
          margin: 50px auto;
        .checkmark {
          width: 100px;
          height: 100px;
          border-radius: 50%;
          display: block;
          stroke-width: 2;
          stroke: #4bb71b;
          stroke-miterlimit: 10;
          box-shadow: inset 0px 0px 0px #4bb71b;
          animation: fill 0.4s ease-in-out 0.4s forwards,
            scale 0.3s ease-in-out 0.9s both;
          position: relative;
          top: 5px;
          right: 5px;
          margin: 0 auto;
        .checkmark__circle {
          stroke-dasharray: 166;
          stroke-dashoffset: 166;
          stroke-width: 2;
          stroke-miterlimit: 10;
          stroke: #4bb71b;
          fill: #fff;
          animation: stroke 0.6s cubic-bezier(0.65, 0, 0.45, 1) forwards;
        .checkmark__check {
          transform-origin: 50% 50%;
          stroke-dasharray: 48;
          stroke-dashoffset: 48;
          animation: stroke 0.3s cubic-bezier(0.65, 0, 0.45, 1) 0.8s forwards;
        @keyframes stroke {
          100% {
            stroke-dashoffset: 0;
        @keyframes scale {
          100% {
            transform: none;
          50% {
            transform: scale3d(1.1, 1.1, 1);
        @keyframes fill {
          100% {
            box-shadow: inset 0px 0px 0px 30px #4bb71b;

{% block content %}
{% endblock content %}


Next, open the payment/templates/payment.html file and the add:

{% extends 'base.html' %}
{% load crispy_forms_tags %}

{% block content %}
    <div class="container mt-5 pt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3>Become a Member!</h3>
                    <div class="card-body">
                        {% crispy form %}
                        <div class="row mt-2">
                            <div class="col-md-12">
                                {% if payment %}
                                    <form action="{% url 'payment-status' %}" method="POST" class="payment-status">
                                        {% csrf_token %}
                                                data-amount="{{ payment.amount }}"
                                                data-currency="{{ payment.currency }}"
                                                data-order_id="{{ }}"
                                                data-buttontext="Pay with Razorpay"
                                                data-name="Tuts-Station Membership"
                                                data-description="Become a Premium Member!"
                                      "{{ }}"
                                      "[email protected]"
                                        <input type="hidden" custom="Hidden Element" name="hidden">
                                {% endif %}
<script type="text/javascript">
    $('.razorpay-payment-button').addClass('btn btn-success');
{% endblock %}

Next, open the payment/templates/callback.html file and the add:

{% extends 'base.html' %}

{% block content %}

    {% if status %}
        <div class="container" style="text-align: center;">
            <div class="success-animation">
              <svg class="checkmark" xmlns="" viewBox="0 0 52 52">
                <circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none" />
                <path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8" />
        <h2 style="text-align: center;">Thank you. Your payment was successful.</h2>
    {% else %}
        <h2 style="text-align: center;">Your Payment is failed! Try again.</h2>
    {% endif %}

    <div class="text-center mt-5">
        <a href="{% url 'payment' %}" class="btn btn-primary" role="button">Buy another one</a>
{% endblock %}
Step 12 : Creating URLs

In this section, we’ll create the urls to access our views.Go to the payment/ file and update it as follows:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.payment, name='payment'),
    path('payment-status', views.payment_status, name='payment-status')

Next, we will require the modify the your root preoject folder lets update the file.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('payment.urls')),
Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python runserver

Next, go to the http://localhost:8000/ address with a web browser.

We can check all these payment in Razorpay dashboard

I Hope It will help you....