How to interact with Smart Contracts using Python and Django.
Tags: webdev, web3, vyper, django
Published: 2024-05-18 07:20:20

In our [previous article](https://dev.to/mosesmuwawu/how-to-interact-with-smart-contracts-locally-using-web3py-2896), 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](https://docs.djangoproject.com/en/5.0/)

- 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`:

```python
# 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)


```

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

`views.py`

```python
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

```

`urls.py`

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

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

```

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

```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>

```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ipxb2az9qsx8pgabooho.jpg)

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!