Open In App

Django – How to add multiple submit button in single form?

Last Updated : 12 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisites:

When we submit the data using the HTML form, it sends the data to the server at a particular URL which is defined in the action attribute. To perform different actions with a single HTML form, we just need to add multiple submit buttons in the form. For example, If you go through the code of the newsletter app, you will find subscribe and unsubscribe buttons in a single HTML form but both perform different actions. 

In this tutorial, we are going to make a newsletter app using Django. We will add subscribe and unsubscribe buttons in a single HTML form. Moreover, We will add or remove the email address of the user from our database according to the user clicks on the subscribe or unsubscribe button.

To create the simple newsletter Django app, follow the below steps.

Create a new Django project

To start a new Django project, your local computer should be satisfied with the prerequisites are given above. Users can use the below command to start a new project.

django-admin startproject newslatter

Next, Go to the project directory.

cd newslatter

Start a newsletter app

To start a new app inside the newsletter project, run the below command inside the project directory.

django-admin startapp appnewslatter

Now, add “appnewslatter” inside the installed_apps section in settings.py of the newsletter project.

path: newslatter/settings.py

Next, Edit the urls.py inside the newsletter folder and add the below code. 

Path: newslatter/urls.py

Filename: urls.py

Python3




from django.contrib import admin
from django.urls import path, include
 
urlpatterns = [
    path('admin/', admin.site.urls),
   
    #including URLS of appnewslatter app
    path("", include('appnewslatter.urls')),
]


Create a new urls.py file inside the “appnewslatter” folder. Now, your project directory should look like the below image.

Edit the urls.py inside the appnewslatter folder. We are adding the URL for the home page.

Path: appnewslattere/urls.py

Filename: urls.py

Python3




from django.urls import path
from . import views
 
urlpatterns = [
    
    # URL to open home page
    path("", views.home, name='home'),
]


Create a “templates” folder inside the appnewslatter folder to store the HTML templates.

path: appnewslatter/templates

Create a news.html file inside the templates folder to add a form for our newslatter app.

Path: appnewslatter/templates/news.html

Add the below code inside the news.html file which includes a single form with 2 submit buttons. Every submits button has a unique name. In the views.py file, We will identify from which button users have sent the post request using the name of the button.

Filename: news.html

HTML




<!DOCTYPE html>
<html>
   
  <head>
    <title>NewsLatter</title>
  </head>
   
  <body>
   
  <!--showing success message-->
  {% if messages %}
    <ul class="messages">
        {% for message in messages %}
            <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>
              {{ message }}</li>
        {% endfor %}
    </ul>
   {% endif %}
     
   <!--Form with multiple submit buttons-->
   <form action="" method="POST">
     <label for="email">Enter your email:</label>
     <input type="email" id="email" name="email" />
      <br> <br>
     <button type="submit" name="subscribe">Subscribe</button>
     <button type="submit" name="unsubscribe">Unsubscribe</button>
   </form>
   
  </body>
</html>


Now, we need to create a table in the database to store the email of the users. We will edit the models.py file.

path: appnewlatter/models.py

Filename: models.py

Python3




from django.db import models
 
# creating database model to store email
class newslatteremail(models.Model):
    userEmail = models.EmailField(max_length=254)
 
    def __str__(self):
        return self.userEmail


Register the created model inside the admin.py file.

Path: appnewslatter/admin.py

Filename: admin.py

Python3




from django.contrib import admin
from .models import newslatteremail
 
# registering the model
admin.site.register(newslatteremail)


After registering the model, we need to migrate it. Users need to run the below 2 commands one by one.

python manage.py makemigrations
python manage.py migrate

Now, we will edit the views.py file and add the code to handle requests from subscribe and unsubscribe buttons. Here, we check that from which submit button we get the post request with the help of the name attribute of the button.

Syntax:

if 'name_of_button' in request.POST:
   # perform some action

Example:

if 'subscribe' in request.POST:
   # add the user email in database
if 'unsubscribe' in request.POST:
   # remove the user email from database

Copy/paste the below code inside the views.py file.

Path: appnewslatter/views.py

Filename: views.py

Python3




from django.shortcuts import render
from django.contrib import messages
from .models import newslatteremail
 
def home(request):
     
    # if post request comes from the subscribe button
    # then saving user email in our database
    if 'subscribe' in request.POST:
        email = newslatteremail()
        email.userEmail = request.POST.get("email")
        email.save()
        messages.info(
            request, 'You have successfully subscribed to our newslatter.')
     
    # if post request comes from the unsubscribe button
    # then deleting the user email from our database
    if 'unsubscribe' in request.POST:
        newslatteremail.objects.get(
            userEmail=request.POST.get("email")).delete()
        messages.info(request, 'sorry to see you!!!')
         
    return render(request, 'news.html')


Finally, we have created a simple newsletter app and learned about how we can add multiple submit buttons in a single HTML form. Let’s run the project and see the output. Users can run the Django app using the below command.

Python manage.py runserver

Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads