DEV Community

Muwawu Moses
Muwawu Moses

Posted on

How to interact with Smart Contracts using Python and Django.

In our previous article, we saw how to locally interact with smart contracts. However, this was through Vs code terminal. Now, it's time to raise the bar and interact with our smart contract through a web browser.

Prerequisites:

  • Prior knowledge in Django

  • Smart contract code already written, compiled and deployed on binance smart chain.

  • ABI and contract address copied and saved.

  • Ganache running on our local machine.

So, we are going to make a few changes in our previous set up.
First, we shall need to install django into our development environment. I will use Django 4.2 for this project.

pip install django==4.2

Next, we are going to start a django project named myproject by running:

django-admin startproject myproject

We then navigate to the root project by running:

cd myproject

Next is to start an app, add it to installed apps and then run migrations.

python3 manage.py startapp myapp, add the newly created app to installed apps and then run migrations: python3 manage.py migrate

After that, it's time to start our building process.

  • First, delete the previous folder vyper_project which contained our python file we used in the previous tutorial.

Navigate to the myapp directory and create there a new file called contracts.py:

# myapp/contracts.py
from web3 import Web3

# Connect to a remote bnb chain node
web3 = Web3(Web3.HTTPProvider('https://data-seed-prebsc-1-s1.binance.org:8545/'))  # or your moralis endpoint, etc.

# ABI of the compiled Vyper contract
abi = [
    {
        "type": "function",
        "name": "sayHello",
        "stateMutability": "nonpayable",
        "inputs": [],
        "outputs": [
            {
                "name": "",
                "type": "string"
            }
        ]
    }
]


# Address of the deployed contract
contract_address = web3.to_checksum_address('0xae95803315d402afb1a24c48e4c3f7d67180747e')  # replace with your contract's address

# Create a contract instance
contract = web3.eth.contract(address=contract_address, abi=abi)

# Call the sayHello function
def call_say_hello():
    try:
        result = contract.functions.sayHello().call()
        return result
    except Exception as e:
        return str(e)


Enter fullscreen mode Exit fullscreen mode

Next, is to create the following files within the myapp directory.

views.py

from django.views.generic import TemplateView
from .contracts import call_say_hello

class HelloMessageView(TemplateView):
    template_name = 'myapp/hello_message.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['message'] = call_say_hello()
        return context

Enter fullscreen mode Exit fullscreen mode

urls.py

# myapp/urls.py
from django.urls import path
from .views import HelloMessageView

urlpatterns = [
    path('', HelloMessageView.as_view(), name='hello_message'),
]

Enter fullscreen mode Exit fullscreen mode

And lastly, create an html file in your templates folder e.g templates/myapp/hello_message.html.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello Message</title>
</head>
<body>
    <h1>Hello Message</h1>
    <p>{{ message }}</p>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

Wow! we are now ready to run our server.

python3 manage.py runserver

The goal here is to print a Hello, World! statement from our smart contract When we open the browser on localhost: 8000, we see the following result:

localhost

This confirms that we have had a successful journey. If you found this article helpful, give me a heart and follow for more. I welcome any kind of interactions in the comment section. Thank you!

Top comments (0)