Create Newsletter app using Mailchimp and Django
Last Updated :
17 Jul, 2024
In this article, we'll use MailChimp and Django to make a simple mailing app. When people subscribe to our app, we'll learn how to create an audience list and save the users in MailChimp using Python.
Have you considered how they could send emails to subscribers with only one click? MailChimp is the greatest email marketing software. It also allows you to manage your audiences and send bulk emails by allowing you to build multiple lists. However, simply sending emails is insufficient. It should have some appealing MailChimp layouts and text, and you may choose preset templates for your email directly.
Create MailChimp Free Account:
To create a MailChimp account and get an API key follow the below steps:
Step 1: Go to MailChimp.com and signup for free. Also, set up the profile of your account.
Step 2: Now, to get the API key, From the bottom left of your screen, Go to the profile>> Extras >> API Key >> Create API Key. Furthermore, it would help if you store your API key. We will use it later in our Django app.
Step 3: Next, we need to create an audience list. Go to https://us14.admin.mailchimp.com/lists/, and click on the Create Audience. Fill in the required details and see your audience on the audience dashboard.
Step 4: Now, we need to get the audience list id. Go to the audience settings -> list id. Store the list id to use it in the Django app.
Create Django APP:
Step 1: Users need to enter the below command into the terminal to create a new Django App.
django-admin startproject mailchimpNewsletter
Step 2: Next, go to the project directory.
cd mailchimpNewsletter
Now, users need to create a views.py file in the project directory. Also, create a templates folder and create a home.html ( templates>> home.html ) ,success.html, and error.html file in that.
Project structure: It should look like this.
Step 3: Before we dive into setting up the project, install the Mailchimp-marketing python library by entering the below command to the project directory.
pip install mailchimp-marketing
Step 4: In this step, we will integrate Mailchimp with the Django App.
- urls.py: Add the below code with the code of the urls.py file. We have set up the URLs for our Django App in this file.
Python
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path("", views.subscribeToNewsLetter, name="subscribeToNewsLetter"),
path("success", views.success, name="success"),
path("error", views.error, name="error"),
]
- views.py: In this file, we will add basic code to subscribe the user to Mailchimp.
Python
from django.shortcuts import redirect, render
from mailchimp_marketing import Client
from mailchimp_marketing.api_client import ApiClientError
api_key = "acfa4fffd113041454c6d953a71fa3e5-us14"
list_id = "f4f5ad20f7"
# function to manage subscriber
def subscribeToNewsLetter(request):
if request.method == "POST":
# getting users input from the form
email = request.POST['email']
firstName = request.POST['firstName']
lastName = request.POST['lastName']
# initializing the mailchimp client with api key
mailchimpClient = Client()
mailchimpClient.set_config({
"api_key": api_key,
})
userInfo = {
"email_address": email,
"status": "subscribed",
"merge_fields": {
"FNAME": firstName,
"LNAME": lastName
}
}
try:
# adding member to mailchimp audience list
mailchimpClient.lists.add_list_member(list_id, userInfo)
return redirect("success")
except ApiClientError as error:
print(error.text)
return redirect("error")
return render(request, "home.html")
def success(request):
return render(request, 'success.html')
def error(request):
return render(request, 'error.html')
- home.html: It is the basic template to collect the user's email, first name, and last name.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Email subscriptions</title>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<style>
form {
position: absolute;
left: 40%;
display: flex;
flex-direction: column;
}
input {
margin: 10px 0;
width: 300px;
height: 50px;
}
button {
width: 300px;
height: 50px;
}
h1 {
color: green;
margin-bottom: 20px;
}
</style>
</head>
<body style="text-align:center">
<h1>GeeksforGeeks</h1>
<h2>Subscribe to Our NewsLetter App</h2>
<!--Email subscription Form -->
<form method="post" action="{% url 'subscribeToNewsLetter' %}">
{% csrf_token %}
<input type="email" name="email" placeholder="Your Email">
<input type="text" name="firstName" placeholder="Your firstName">
<input type="text" name="lastName" placeholder="Your lastName">
<button class="btn btn-secondary" type="submit">Submit</button>
</form>
</body>
</html>
- success.html: We will redirect a user to this template when they subscribe to our newsletter successfully.
HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>successfully</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="display-4">Awesom</h1>
<p class="lead">You are successful to signup in newsletter website,
please look forward.</p>
</div>
</div>
</body>
</html>
- error.html: We will redirect a user to this template when some error occurs while subscribing to our newsletter.
HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Failure</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="display-4">Uh oh!</h1>
<p class="lead">Contact the developer</p>
<form class="" action="/error" method="post">
<button class="btn btn-lg " type="submit"
name="button">Try again</button>
</form>
</div>
</div>
</body>
</html>
Step 5: Add 'DIRS' : [os.path.join.(BASE_DIR, 'templates')] in your templates list.
Step 6: To run the project on your terminal, go to the project directory and enter the below command.
python manage.py runserver
Output: You will see that the app is running successfully on localhost:8000.
At last, in MailChimp, you can go to the Audience >> All contacts, and you will see the list of all added contacts.
Similar Reads
How to Create an App in Django ?
In Django, an app is a web application that performs a specific functionality, such as blog posts, user authentication or comments. A single Django project can consist of multiple apps, each designed to handle a particular task. Each app is a modular and reusable component that includes everything n
3 min read
Realtime chat app using Django
Chat Room has been the most basic step toward creating real-time and live projects. The chat page that we will create will be a simple HTML boilerplate with a simple h1 text with the name of the current user and a link to log out to the user who is just logged in. You may need to comment on the line
11 min read
How to Create a Basic Project using MVT in Django ?
Prerequisite - Django Project MVT Structure Assuming you have gone through the previous article. This article focuses on creating a basic project to render a template using MVT architecture. We will use MVT (Models, Views, Templates) to render data to a local server. Create a basic Project: To in
2 min read
How to Create a basic API using Django Rest Framework ?
Django REST Framework (DRF) is a powerful extension of Django that helps you build APIs quickly and easily. It simplifies exposing your Django models as RESTfulAPIs, which can be consumed by frontend apps, mobile clients or other services.Before creating an API, there are three main steps to underst
4 min read
How to create a form using Django Forms ?
This article explains how to create a basic form using various form fields and attributes. Creating a form in Django is very similar to creating a model, you define the fields you want and specify their types. For example, a registration form might need fields like First Name (CharField), Roll Numbe
2 min read
Create Task Management System using Django
Task management systems are essential tools for individuals and organizations to organize, track, and prioritize tasks efficiently. In this article, we'll explore how to build a task management system using django in Python.Task Management System using DjangoBelow, are the implementations of the Tas
15+ min read
Creating and Using Serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other conten
3 min read
Create URL Bookmark Manager Using Django
This article explains how to make a tool called a Bookmark Organizer with Django for a website. With this tool, we can add, create, update, delete, and edit bookmarks easily. We just need to input the title and link, and we can save them. Then, we can click on the link anytime to visit the website.
5 min read
Create a new Django project in Pycharm using Pycharm Terminal
PyCharm is one of the most popular Python-IDE developed by JetBrains used for performing scripting in Python language. PyCharm provides many useful features like Code completion and inspection, Debugging process, support for various programming frameworks such as Flask and Django, Package Management
2 min read
How to create a new project in Django using Firebase Database?
Django is a Python-based web framework that allows you to quickly create efficient web applications. If you are new to Django then you can refer to Django Introduction and Installation. Here we are going to learn How to create a Django project using Firebase as Database . How to create a new projec
3 min read