Logo

dev-resources.site

for different kinds of informations.

How to interact with Smart Contracts using Python and Django.

Published at
5/18/2024
Categories
webdev
web3
vyper
django
Author
mosesmuwawu
Categories
4 categories in total
webdev
open
web3
open
vyper
open
django
open
Author
11 person written this
mosesmuwawu
open
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!

vyper Article's
24 articles in total
Favicon
Vyper - Write your First Python Smart Contract (Series)
Favicon
vyper挺好玩的
Favicon
How to use 'initializes' and 'exports' in vyper: Modular Vyper code arrangement.
Favicon
A Simple Vyper smart contract to fetch the price of BTC using Chainlink and Apeworx.
Favicon
Vyper beginner's tutorial: Variables.
Favicon
Mastering Vyper Functions(part1 )
Favicon
How to compile, deploy and interact with smart contracts using Apeworx(ape) and VS Code.
Favicon
Vyper: For loops and Arrays.
Favicon
Mastering functions in Vyper(part2)
Favicon
Vyper Beginner's tutorial: Syntax and Structure.
Favicon
How to interact with Smart Contracts using Python and Django.
Favicon
How to Interact with Smart Contracts locally using web3.py
Favicon
Writing Smart Contracts using Vyper, Remix IDE and deploying them on BNB Smart Chain.
Favicon
Create your own Uniswap DeFi Application🦄! From scratch using Vyper & Python🐍
Favicon
Challenge #2: 🪙 Multi Token Vendor | Speedrun Ethereum With Vyper
Favicon
Introduction to EVM Smart Contract development
Favicon
Challenge #1: 🥩 Decentralized Staking App | Speedrun Ethereum With Vyper 🐍
Favicon
Challenge #0: 🖼️ Simple NFT Example | Speedrun Ethereum With Vyper 🐍
Favicon
Understanding Chainlink VRF: A Tool for Random Number Generation on the Blockchain
Favicon
Constant Product Market Maker (CAMM): The standard in Decentralized Finance
Favicon
Compiling and testing Vyper contract using Foundry
Favicon
Usando constant e immutable para reduzir o custo de gás
Favicon
ERC20 Token with Vyper and Brownie
Favicon
Try Vyper in Truffle v5.

Featured ones: