top

Creating Your First Offline Payment Wallet With Django

Choosing the right web development framework among few frameworks on the market is a big deal. Django framework is an easy choice for most of the companies. What is Django? Who uses it? And let’s figure out how can we make offline payment with it?  What is Django?Django is a powerful tool for speeding up common web development tasks while keeping the design clean and pragmatic.  Django is a high-level open-source collection of libraries written in Python and also one of the most popular server-side web frameworks.Who uses Django?Django is being used from daily newspapers to social media and sharing sites. Originally Django was developed to use in the newsroom. Daily publications like The Guardian and Washington post rely on it. Startups companies like Disqus and Eventbrite also relied on Django to enhance.When is Django Development the right choice?It is important to understand when this framework can serve the best. Django will be the best choice only if:Only when the app is secureWhen a huge degree of scalability is expectedWhen the client needs an API back-end or web appAre you aware of making offline payment with Django?Let’s discuss how to make offline payment using Django in three parts:In the first part, we will discuss setting up Django, creating models, SQLite (using Django shell, return self etc., ) forms, and the django-admin. In part 2, we shall talk about Jinja templating,HTML, CSS, JS, Static, Bootstrap and the third. The final part can be a closure on what can be done next.Now, we are going to create a wallet for implementing offline payment gateway which will help to track the offline money you owe or are owed. We will call our application debt Manager. So let's get started. As the first part will involve setting up of Django for this project, you can skip this if you have Django installed and running on your computer. Setting up project environmentThis Django offline payment tutorial assumes a version of python 2( 2.6 or above) and pip installed. To set up Django first we need to create a virtual environment.Why use a Virtual Environment?A virtual environment helps to make an isolated python environment, you must be thinking how can this be useful? For understanding let us take an example say we have two different projects requiring two different versions of a library so saving the file in /usr/lib/python2.7/site-packages (or any other location) may lead to need to upgrading the file and downgrading it based on your needs, so basically using a virtual environment is a solution to this problem as you can create different environments for different applications. It is possible that there are two python applications using a different version of a python library and you require to run them simultaneously, then in such cases, the virtual environment comes in handy. There is a possibility that your python program makes changes to any other software dependencies(bits of software on which a software depends on) and settings which may lead to the other software malfunctioning or even not running, using a virtual environment helps us to prevent such problems.  This tool in python is known as virtualenv and we can install it from the command line with pip as follows:pip install virtualenvThe output from your command line should look something like thisuser@user-Inspiron-5558:~$ pip install virtualenv Collecting virtualenv Downloading virtualenv-15.1.0-py2.py3-none-any.whl (1.8MB)     100% |################################| 1.8MB 323kB/s Installing collected packages: virtualenv Successfully installed virtualenv-15.1.0Now create your own environment in the desired folderuser@user-Inspiron-5558:~$ virtualenv venvYou can name the virtual environment anything you like. Now switch to the environment and run it(for Windows use):venv\scripts\activateThe next command line statements will have (venv) at the beginning which tells us that we are using the virtual environment. Our next step to set up the project is to install Django:Installing DjangoSince we are running a virtual environment, installing Django is super easy, just type the command, notice that the Django command 1.11.2 this tells the pip to install this particular version of the Django otherwise if we wouldn't have mentioned the version it would have installed the latest stable version of Django that is availablepip install django==1.11.2Starting the projectOnce we successfully installed Django, we will now create our projects by typing the following in the project where you want to create the projectdjango-admin startproject debtManagerLet’s look at what startproject command has created:debtManager/   manage.py   debtManager/     __init__.py     settings.py     urls.py     wsgi.pySetting up DatabasePython comes with an inbuilt SQLite database which can ease out the process of dealing with the database information. Now, in our project of we will definitely need a database to store the user information and other details like saying the account balance, to create the database go to the project folder in the command line and type the following commandpython manage.py migrateThe migrate command creates an SQLite database which will create a new database with all the necessary tables that are necessary initially, remember to run this command whenever you make a new table or do any changes to the structure of the table.The Development ServerNow let's check if our application works, to start the development server, on the command line type:python manage.py runserverIf everything works fine then the output on the command will be something like this,Performing system checks... System check identified no issues (0 silenced). May 16, 2017 - 16:48:29 Django version 1.11, using settings 'debtManager.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK.The above screen will appear when you hit http://localhost:8000orhttp://127.0.0.1 in your browser, so congratulations your project has been working.The Django AdminFor most of the website has an admin interface is very much essential for back-end management i.e. managing various information and content of the website. So, with most of the technologies in the market we have to build this interface but this is not the case with Django, there is already an inbuilt integrated website for managing all data from the databases can be viewed in the interface and other functions can also be managed from here which we will be learning about as we progress through it.To access this admin interface hit http://127.0.0.1/admin on a browser, it will redirect you to a login page, to login we need to create credentials of superuser, for this go to the command line terminal,(venv) user@user-Inspiron-5558:~$ python manage.py createsuperuserIt will ask you to enter credentials, I will show an example of it,Username: admin Email address: admin@example.com Password: ********** Password (again): ********* Superuser created successfully.You can use same credentials created above to login to the Django admin and on logging in you will see a screen like this,From here you can manage the users, assign them privileges and manage all your databases and models, this will come in handy as we make login/sign up for the users to our application, which we will learn in the next part of this tutorial.In this article, we learned about setting up the project like, setting up virtual environment, installing Django, setting up offline payment with Django, the databases and the django-admin , in the coming articles we will progress with the project on how to integrate offline payment wallet with Django, till then, Happy Coding, Cheers!!In part 1, we had set up Django and the databases correctly, without wasting any further time let’s get our hands dirty by writing some code.To make the wallet functional and private we need to provide a login functionality to our users so they can login and store their information and details, so we will go on to build the login functionality, for this let us create an app called accounts in our Django project, get into the project directory and type,python manage.py startapp accountsThe app will be created and then we will have to register this application in django settings.py after which the INSTALLED_APPS section will look like thisINSTALLED_APPS = [        'django.contrib.admin',        'django.contrib.auth', #<-- This one        'django.contrib.contenttypes',        'django.contrib.sessions',        'django.contrib.messages',        'django.contrib.staticfiles',        'accounts' ]Notice that Django contains several other built in applications to make our work easy one of which is the auth app, we will be using it to make the login system in Django. To use this we will need to add the urls from this application to urls.py. We will create a file called urls.py inside account application to serve its own urls, this inbuilt application provides us with several authentication views like:accounts/login/ [name='login'] accounts/logout/ [name='logout'] accounts/password_change/ [name='password_change'] accounts/password_change/done/ [name='password_change_done'] accounts/password_reset/ [name='password_reset'] accounts/password_reset/done/ [name='password_reset_done'] accounts/reset/<uidb64>/<token>/ [name='password_reset_confirm'] accounts/reset/done/ [name='password_reset_complete']This can make out tasks a lot easier, we just have to write the code for templates now, the rest has already been done for us by django. So lets add to urls.py created in the project folder,url(r'^accounts/', include('django.contrib.auth.urls')),Once all this has been done , now lets create the templates, to do this we create a folder in the project directory called Templates to store all the templates and create a subdirectory called registration which will store all the views related to the account application. Now we need to define the directly where Django should look for the templates. For this go to settings.py and make a change to Templates which should look like this now,TEMPLATES = [   {       ...       'DIRS': [os.path.join(BASE_DIR, 'Templates')],       ...   }, ]Now let us change the LOGIN_REDIRECT_URL to make sure our user lands on the homepage after the successful login, for this add this to the end of settings.pyLOGIN_REDIRECT_URL = '/accounts/profile'Login TemplateEverything is now set up, now let’s create our login template, inside the accounts folder( remember we created inside Templates folder) create a page called login.html and write the following code:<h2>Login</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form>We have created a post request to send the form information to the server {% csrf_token %} helps to prevent XSS attacks and {{ form.as_p }} does all the magic in loading the contents here, On Making the template of the login now let us try to access the page, but wait we haven't told django to where to look for routes here, for telling django we need to provide the path of urls.pycreated by us to the main project’s urls.py so go to the file in the main project directory and add the following line,url(r'^accounts/', include('accounts.urls'))This helps in making sure that any requests coming on the accounts/ route are directed to the urls.py in the accounts application. Now we are ready to launch our application, go to the project directory from the console and typepython manage.py runserverthe program should start running and to test if our login page is working let's check in the browser, go to the browser and point to http://localhost:8000/accounts/login it should show us the following page,The Login pageOur login page should look like somewhat above, now to test it we need to log in with the correct credentials, remember we created credentials for superuser in the first tutorial, if not then you can create superuser and log in using the same credentials, if the credentials are correct then you should see a screen like-Error screen after successful loginThe above error screen is produced as we have not defined a view for the next page so let’s do that but before that let's create a very basic sign up page, we have an inbuilt UserCreationForm which we will use, switch to views.py and type the following,from django.shortcuts import render from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from django.shortcuts import redirect def signup(request):  if request.method == 'POST':      form = UserCreationForm(request.POST)      if form.is_valid():          form.save()          username = form.cleaned_data.get('username')          password = form.cleaned_data.get('password1')          user =authenticate(username=username,password=password)          login(request, user)          return redirect('profile')   else:      form = UserCreationForm()      return render(request, 'registration/signup.html', {'form': form})And then let us define the routes by adding,from .views import signup urlpatterns = [                   .....       url(r'^signup/$', signup, name='signup'),                   ..... ]As we had done for login.html in the same place we will create a template for signup.html as,<h2>Sign up</h2> <form method="post">   {% csrf_token %}   {{ form.as_p }}   <button type="submit">Sign up</button> </form>To check we will again go back to our browser and point to  http://localhost:8000/accounts/signup  and you should be able to see the sign-up page as.Sign up pageviewNow we can see from our views that this sign up page is redirecting users to the profile page only after logging the user in, so this will also give error page as of now, now let's create the user profile page, let's go to our Template folder and create a file called profile.html. In this just write,Hello {{request.user.username}} !! <br><br> <a href="{% url 'logout' %}">logout</a>So in this template, we have first greeted the user with the hello statement and then given an option for a user to logout, by clicking out the logout button for this let us tell django first where to take the user on logout so insettings.pyadd the following line at the bottomLOGOUT_REDIRECT_URL = '/accounts/login'After this let’s create a simple view for profile so in views.py add the following code,def profile(request): return render(request,'profile.html')This will produce the following output, on log inuser profileNow we have handled the complete user authentication, you can try playing around with colors make it more beautiful with ease using CSS and Bootstrap, in the next section (Part-3), I would tell you how to add the basic transaction feature from one user to another using just usernames, which will also take you to the next advanced steps which can be done after completing this.In part-2, we have successfully created a login system for the users now let us work on providing the main functionality which is the wallet management and get things working.Let’s look into the steps for Django offline wallet management:Step 1:  Display the balance of each personThe very first thing before starting on with the transaction is the need to display the balance of each person which we will be storing in a table, so let’s create it, in accounts/models.py we create a model called balance.from django.contrib.auth.models import User class balance(models.Model):        user = models.ForeignKey(User)        balance = models.IntegerField(default = 0)Notice that Username will be the ForeignKey as we are mapping balance with the given user. When we have successfully created the table now we migrate, on terminal we writepython manage.py makemigrations python manage.py migrateStep 2:  Display the balance of a particular userOur next step will be to display the balance of a particular user in the profile dashboard which we have created in the previous part, now let us write a query to fetch balance for the user and send it to the front-end for displaying it. Below is the updated code in accounts/views.py to achieve this.from models import balance def profile(request):     user = balance.objects.get(user=request.user     return render(request,'profile.html',{"balance":user.balance})Please note that we are fetching the balance of the user in from the database at the time of showing the profile but we have not saved it into database till now so this may break our code so to make this work we have to insert this record into the balance table at the time of profile creation of the user in the signup function so we add the following lines to the code inside the if block in the signup function which will set the default balance of the user to 0 initially in the balance model.instance = balance(user = request.user, balance = 0) instance.save()Step 3:  Display the balance to the userNow we have to display the balance to the user, so to do this we just have to display the variable balance which we have sent int the profile function in profile.html.Balance: {{balance}}Adding above line of code in the file should now display the balance of the user on logging in.Step 4:  Setting up offline paymentWe are able to display the balance to the user, Now we come to our last step of setting up offline payment with Django, wherein the user can transfer an amount from his wallet to wallet to some other user which will lead to deduction of the amount from the wallet of the user and addition of amount in the wallet of another user, so let us try to implement it.Lets start with the front-end where we make a form where the user can insert the username and amount for making the transfer. So we add following lines to profile.html.<form method="post"> <input type="text" name="username" placeholder="Enter Username"> <input type="text" name="amount" placeholder="Enter Amount"> <input type="submit" value="Submit"> </form>Now we again refresh the page to see the following pageLet’s write the back-end for handling this form now, as discussed earlier when a transfer request is made we have to deduct the amount from the user and put it in wallet of some other user, which is just a matter of few queries, lets see the code for this.def profile(request): msg="" if request.method == "POST":   try:     username = request.POST["username"]     amount = request.POST["amount"]     senderUser= User.objects.get(username=request.user.username)     receiverUser=User.objects.get(username=username)     sender = balance.objects.get(user = senderUser)     receiver = balance.objects.get(user = receiverUser)                sender.balance = sender.balance - int(amount)     receiver.balance = receiver.balance + int(amount)     sender.save()     receiver.save()     msg = "Transaction Success"   except Exception as e:     print(e)     msg = "Transaction Failure, Please check and try again" user = balance.objects.get(user=request.user) return render(request,'profile.html',{"balance":user.balance,"msg":msg})In the above code in the try block we are getting the form data from the user try to search for the credentials for the receiver and the sender and fetch their balance from the balance table and add the amount to be transferred from to the receiver’s wallet and deduct the same from the sender’s wallet and we return the transaction message to the profile.html which can be displayed in the same way as discussed earlier.That concludes this part of the article, the complete code for this can be found on this repository, free to make any issue or pull request, Further steps for Implementing offline payment gateway in Django may include:Adding transaction history page for a particular user which can be done by saving the transactions history in a new table having fields sender, receiver and amount.Display more accurate error messages on transaction failure.Adding features like notification and messaging in the profile dashboard.Making the pages look good using CSS and Bootstrap.Any other enhancements you may think up.Feel free to fork and contribute to the repository and leave a comment here if help is needed. That is all for this article, I hope this article helped you to learn how to set up an offline payment with Django. Thanks for reading.
Rated 4.0/5 based on 58 customer reviews
Normal Mode Dark Mode

Creating Your First Offline Payment Wallet With Django

Pratik Singh Chauhan
Blog
24th May, 2018
Creating Your First Offline Payment Wallet With Django

Choosing the right web development framework among few frameworks on the market is a big deal. Django framework is an easy choice for most of the companies. What is Django? Who uses it? And let’s figure out how can we make offline payment with it?  

What is Django?

Django is a powerful tool for speeding up common web development tasks while keeping the design clean and pragmatic.  Django is a high-level open-source collection of libraries written in Python and also one of the most popular server-side web frameworks.

Who uses Django?

Django is being used from daily newspapers to social media and sharing sites. Originally Django was developed to use in the newsroom. Daily publications like The Guardian and Washington post rely on it. Startups companies like Disqus and Eventbrite also relied on Django to enhance.

When is Django Development the right choice?

It is important to understand when this framework can serve the best. Django will be the best choice only if:

  • Only when the app is secure
  • When a huge degree of scalability is expected
  • When the client needs an API back-end or web app

Are you aware of making offline payment with Django?

Let’s discuss how to make offline payment using Django in three parts:

In the first part, we will discuss setting up Django, creating models, SQLite (using Django shell, return self etc., ) forms, and the django-admin. In part 2, we shall talk about Jinja templating,HTML, CSS, JS, Static, Bootstrap and the third. The final part can be a closure on what can be done next.

Now, we are going to create a wallet for implementing offline payment gateway which will help to track the offline money you owe or are owed. We will call our application debt Manager. So let's get started. As the first part will involve setting up of Django for this project, you can skip this if you have Django installed and running on your computer. 

Setting up project environment

This Django offline payment tutorial assumes a version of python 2( 2.6 or above) and pip installed. To set up Django first we need to create a virtual environment.

Why use a Virtual Environment?

A virtual environment helps to make an isolated python environment, you must be thinking how can this be useful? For understanding let us take an example say we have two different projects requiring two different versions of a library so saving the file in /usr/lib/python2.7/site-packages (or any other location) may lead to need to upgrading the file and downgrading it based on your needs, so basically using a virtual environment is a solution to this problem as you can create different environments for different applications. It is possible that there are two python applications using a different version of a python library and you require to run them simultaneously, then in such cases, the virtual environment comes in handy.

There is a possibility that your python program makes changes to any other software dependencies(bits of software on which a software depends on) and settings which may lead to the other software malfunctioning or even not running, using a virtual environment helps us to prevent such problems.

 This tool in python is known as virtualenv and we can install it from the command line with pip as follows:

pip install virtualenv

The output from your command line should look something like this

user@user-Inspiron-5558:~$ pip install virtualenv
Collecting virtualenv
Downloading virtualenv-15.1.0-py2.py3-none-any.whl (1.8MB)
    100% |################################| 1.8MB 323kB/s
Installing collected packages: virtualenv
Successfully installed virtualenv-15.1.0

Now create your own environment in the desired folder

user@user-Inspiron-5558:~$ virtualenv venv

You can name the virtual environment anything you like. Now switch to the environment and run it(for Windows use):

venv\scripts\activate

The next command line statements will have (venv) at the beginning which tells us that we are using the virtual environment. Our next step to set up the project is to install Django:

Installing Django

Since we are running a virtual environment, installing Django is super easy, just type the command, notice that the Django command 1.11.2 this tells the pip to install this particular version of the Django otherwise if we wouldn't have mentioned the version it would have installed the latest stable version of Django that is available

pip install django==1.11.2

Starting the project

Once we successfully installed Django, we will now create our projects by typing the following in the project where you want to create the project

django-admin startproject debtManager

Let’s look at what startproject command has created:

debtManager/
  manage.py
  debtManager/
    __init__.py
    settings.py
    urls.py
    wsgi.py

Setting up Database

Python comes with an inbuilt SQLite database which can ease out the process of dealing with the database information. Now, in our project of we will definitely need a database to store the user information and other details like saying the account balance, to create the database go to the project folder in the command line and type the following command

python manage.py migrate

The migrate command creates an SQLite database which will create a new database with all the necessary tables that are necessary initially, remember to run this command whenever you make a new table or do any changes to the structure of the table.

The Development Server

Now let's check if our application works, to start the development server, on the command line type:

python manage.py runserver

If everything works fine then the output on the command will be something like this,

Performing system checks...

System check identified no issues (0 silenced).
May 16, 2017 - 16:48:29
Django version 1.11, using settings 'debtManager.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

Django powered page

The above screen will appear when you hit http://localhost:8000orhttp://127.0.0.1 in your browser, so congratulations your project has been working.

The Django Admin

For most of the website has an admin interface is very much essential for back-end management i.e. managing various information and content of the website. So, with most of the technologies in the market we have to build this interface but this is not the case with Django, there is already an inbuilt integrated website for managing all data from the databases can be viewed in the interface and other functions can also be managed from here which we will be learning about as we progress through it.

To access this admin interface hit http://127.0.0.1/admin on a browser, it will redirect you to a login page, to login we need to create credentials of superuser, for this go to the command line terminal,

(venv) user@user-Inspiron-5558:~$ python manage.py createsuperuser

It will ask you to enter credentials, I will show an example of it,

Username: admin
Email address: admin@example.com
Password: **********
Password (again): *********
Superuser created successfully.

You can use same credentials created above to login to the Django admin and on logging in you will see a screen like this,

Django administrationFrom here you can manage the users, assign them privileges and manage all your databases and models, this will come in handy as we make login/sign up for the users to our application, which we will learn in the next part of this tutorial.

In this article, we learned about setting up the project like, setting up virtual environment, installing Django, setting up offline payment with Django, the databases and the django-admin , in the coming articles we will progress with the project on how to integrate offline payment wallet with Django, till then, Happy Coding, Cheers!!

In part 1, we had set up Django and the databases correctly, without wasting any further time let’s get our hands dirty by writing some code.

To make the wallet functional and private we need to provide a login functionality to our users so they can login and store their information and details, so we will go on to build the login functionality, for this let us create an app called accounts in our Django project, get into the project directory and type,

python manage.py startapp accounts

The app will be created and then we will have to register this application in django settings.py after which the INSTALLED_APPS section will look like this

INSTALLED_APPS = [
       'django.contrib.admin',
       'django.contrib.auth', #<-- This one
       'django.contrib.contenttypes',
       'django.contrib.sessions',
       'django.contrib.messages',
       'django.contrib.staticfiles',
       'accounts'
]

Notice that Django contains several other built in applications to make our work easy one of which is the auth app, we will be using it to make the login system in Django. To use this we will need to add the urls from this application to urls.py. We will create a file called urls.py inside account application to serve its own urls, this inbuilt application provides us with several authentication views like:

accounts/login/ [name='login']
accounts/logout/ [name='logout']
accounts/password_change/ [name='password_change']
accounts/password_change/done/ [name='password_change_done']
accounts/password_reset/ [name='password_reset']
accounts/password_reset/done/ [name='password_reset_done']
accounts/reset/<uidb64>/<token>/ [name='password_reset_confirm']
accounts/reset/done/ [name='password_reset_complete']

This can make out tasks a lot easier, we just have to write the code for templates now, the rest has already been done for us by django. So lets add to urls.py created in the project folder,

url(r'^accounts/', include('django.contrib.auth.urls')),

Once all this has been done , now lets create the templates, to do this we create a folder in the project directory called Templates to store all the templates and create a subdirectory called registration which will store all the views related to the account application. Now we need to define the directly where Django should look for the templates. For this go to settings.py and make a change to Templates which should look like this now,

TEMPLATES = [
  {
      ...
      'DIRS': [os.path.join(BASE_DIR, 'Templates')],
      ...
  },
]

Now let us change the LOGIN_REDIRECT_URL to make sure our user lands on the homepage after the successful login, for this add this to the end of settings.py

LOGIN_REDIRECT_URL = '/accounts/profile'

Login Template

Everything is now set up, now let’s create our login template, inside the accounts folder( remember we created inside Templates folder) create a page called login.html and write the following code:

<h2>Login</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>

We have created a post request to send the form information to the server {% csrf_token %} helps to prevent XSS attacks and {{ form.as_p }} does all the magic in loading the contents here, On Making the template of the login now let us try to access the page, but wait we haven't told django to where to look for routes here, for telling django we need to provide the path of urls.pycreated by us to the main project’s urls.py so go to the file in the main project directory and add the following line,

url(r'^accounts/', include('accounts.urls'))

This helps in making sure that any requests coming on the accounts/ route are directed to the urls.py in the accounts application. Now we are ready to launch our application, go to the project directory from the console and type

python manage.py runserver

the program should start running and to test if our login page is working let's check in the browser, go to the browser and point to http://localhost:8000/accounts/login it should show us the following page,
The Login page

Our login page should look like somewhat above, now to test it we need to log in with the correct credentials, remember we created credentials for superuser in the first tutorial, if not then you can create superuser and log in using the same credentials, if the credentials are correct then you should see a screen like-
Error screen after successful login

The above error screen is produced as we have not defined a view for the next page so let’s do that but before that let's create a very basic sign up page, we have an inbuilt UserCreationForm which we will use, switch to views.py and type the following,

from django.shortcuts import render
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import redirect
def signup(request):
 if request.method == 'POST':
     form = UserCreationForm(request.POST)
     if form.is_valid():
         form.save()
         username = form.cleaned_data.get('username')
         password = form.cleaned_data.get('password1')
         user =authenticate(username=username,password=password)
         login(request, user)
         return redirect('profile')
  else:
     form = UserCreationForm()
     return render(request, 'registration/signup.html', {'form': form})

And then let us define the routes by adding,

from .views import signup
urlpatterns = [
                  .....
      url(r'^signup/$', signup, name='signup'),
                  .....
]

As we had done for login.html in the same place we will create a template for signup.html as,

<h2>Sign up</h2>
<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Sign up</button>
</form>

To check we will again go back to our browser and point to  http://localhost:8000/accounts/signup  and you should be able to see the sign-up page as.
Sign up pageview

Now we can see from our views that this sign up page is redirecting users to the profile page only after logging the user in, so this will also give error page as of now, now let's create the user profile page, let's go to our Template folder and create a file called profile.html. In this just write,

Hello {{request.user.username}} !! <br><br>
<a href="{% url 'logout' %}">logout</a>

So in this template, we have first greeted the user with the hello statement and then given an option for a user to logout, by clicking out the logout button for this let us tell django first where to take the user on logout so insettings.pyadd the following line at the bottom

LOGOUT_REDIRECT_URL = '/accounts/login'

After this let’s create a simple view for profile so in views.py add the following code,

def profile(request):
return render(request,'profile.html')

This will produce the following output, on log in
user profile

Now we have handled the complete user authentication, you can try playing around with colors make it more beautiful with ease using CSS and Bootstrap, in the next section (Part-3), I would tell you how to add the basic transaction feature from one user to another using just usernames, which will also take you to the next advanced steps which can be done after completing this.

In part-2, we have successfully created a login system for the users now let us work on providing the main functionality which is the wallet management and get things working.

Let’s look into the steps for Django offline wallet management:

Step 1:  Display the balance of each person

The very first thing before starting on with the transaction is the need to display the balance of each person which we will be storing in a table, so let’s create it, in accounts/models.py we create a model called balance.

from django.contrib.auth.models import User
class balance(models.Model):
       user = models.ForeignKey(User)
       balance = models.IntegerField(default = 0)

Notice that Username will be the ForeignKey as we are mapping balance with the given user. When we have successfully created the table now we migrate, on terminal we write

python manage.py makemigrations
python manage.py migrate

Step 2:  Display the balance of a particular user

Our next step will be to display the balance of a particular user in the profile dashboard which we have created in the previous part, now let us write a query to fetch balance for the user and send it to the front-end for displaying it. Below is the updated code in accounts/views.py to achieve this.

from models import balance
def profile(request):
    user = balance.objects.get(user=request.user
    return render(request,'profile.html',{"balance":user.balance})

Please note that we are fetching the balance of the user in from the database at the time of showing the profile but we have not saved it into database till now so this may break our code so to make this work we have to insert this record into the balance table at the time of profile creation of the user in the signup function so we add the following lines to the code inside the if block in the signup function which will set the default balance of the user to 0 initially in the balance model.

instance = balance(user = request.user, balance = 0)
instance.save()

Step 3:  Display the balance to the user

Now we have to display the balance to the user, so to do this we just have to display the variable balance which we have sent int the profile function in profile.html.

Balance: {{balance}}

Adding above line of code in the file should now display the balance of the user on logging in.

setting up offline payment

Step 4:  Setting up offline payment

We are able to display the balance to the user, Now we come to our last step of setting up offline payment with Django, wherein the user can transfer an amount from his wallet to wallet to some other user which will lead to deduction of the amount from the wallet of the user and addition of amount in the wallet of another user, so let us try to implement it.

Lets start with the front-end where we make a form where the user can insert the username and amount for making the transfer. So we add following lines to profile.html.

<form method="post">
<input type="text" name="username" placeholder="Enter Username">
<input type="text" name="amount" placeholder="Enter Amount">
<input type="submit" value="Submit">
</form>

Now we again refresh the page to see the following page

Let’s write the back-end for handling this form now, as discussed earlier when a transfer request is made we have to deduct the amount from the user and put it in wallet of some other user, which is just a matter of few queries, lets see the code for this.

def profile(request):
msg=""
if request.method == "POST":
  try:
    username = request.POST["username"]
    amount = request.POST["amount"]
    senderUser= User.objects.get(username=request.user.username)
    receiverUser=User.objects.get(username=username)
    sender = balance.objects.get(user = senderUser)
    receiver = balance.objects.get(user = receiverUser)           
    sender.balance = sender.balance - int(amount)
    receiver.balance = receiver.balance + int(amount)
    sender.save()
    receiver.save()
    msg = "Transaction Success"
  except Exception as e:
    print(e)
    msg = "Transaction Failure, Please check and try again"
user = balance.objects.get(user=request.user)
return render(request,'profile.html',{"balance":user.balance,"msg":msg})

In the above code in the try block we are getting the form data from the user try to search for the credentials for the receiver and the sender and fetch their balance from the balance table and add the amount to be transferred from to the receiver’s wallet and deduct the same from the sender’s wallet and we return the transaction message to the profile.html which can be displayed in the same way as discussed earlier.

That concludes this part of the article, the complete code for this can be found on this repository, free to make any issue or pull request, Further steps for Implementing offline payment gateway in Django may include:

  1. Adding transaction history page for a particular user which can be done by saving the transactions history in a new table having fields sender, receiver and amount.
  2. Display more accurate error messages on transaction failure.
  3. Adding features like notification and messaging in the profile dashboard.
  4. Making the pages look good using CSS and Bootstrap.
  5. Any other enhancements you may think up.

Feel free to fork and contribute to the repository and leave a comment here if help is needed. That is all for this article, I hope this article helped you to learn how to set up an offline payment with Django. Thanks for reading.

Pratik Singh

Pratik Singh Chauhan

Blog author

Pratik is a self taught programmer and loves to share his knowledge,from the Indian Institute of Technology, the best engineering colleges in India, is a Python and JavaScript developer and currently working on challenges in the field of machine learning.

Leave a Reply

Your email address will not be published. Required fields are marked *

SUBSCRIBE OUR BLOG

Follow Us On

Share on

other Blogs

20% Discount