6 min read

Django is an open source web framework that enables you to build clean and feature-rich web applications with minimal time and effort. Django is written in Python, a general purpose language that is well-suited for developing web applications. Social bookmarking is one such application.

Inviting friends via email

Enabling our users to invite their friends carries many benefits. People are more likely to join our site if their friends are already using it. After they join, they will also invite their friends, and so on, which means an increasing number of users for our application. Therefore, it is a good idea to offer an “Invite a friend” feature. This is actually a common functionality found in many Web 2.0 applications.

Building this feature requires the following components:

  • An Invitation data model to store invitations in the database
  • A form in which users can type the emails of their friends and send invitations
  • An invitation email with an activation link
  • A mechanism for processing activation links sent in email

Throughout this article, we will implement each component. But because this article involves sending emails, we first need to configure Django to send emails by adding some options to the settings.py file. So, open the settings.py file and add the following lines to it:

SITE_HOST = '127.0.0.1:8000'
DEFAULT_FROM_EMAIL =
'Django Bookmarks <[email protected]>'

EMAIL_HOST = 'mail.yourisp.com'
EMAIL_PORT = ''
EMAIL_HOST_USER = 'username'
EMAIL_HOST_PASSWORD = 'password'

Let’s see what each variable does.

  • SITE_HOST: This is the host name of your server. Leave it as 127.0.0.1:8000 for now. We will change this, when we deploy our server.
  • DEFAULT_FROM_EMAIL: This is the email address that appears in the From field of emails sent by Django.
  • EMAIL_HOST: This is the host name of your email server. If you are using a development machine that doesn’t run a mail server (which is most likely the case), then you need to put your ISP’s outgoing email server here. Contact your ISP for more information.
  • EMAIL_PORT: This refers to the port number of the outgoing email server. If you leave it empty, the default value (25) will be used. You also need to obtain this from your ISP.
  • EMAIL_HOST_USER and EMAIL_HOST_PASSWORD : This refers to the username and password for the outgoing email server. For the host username, input your username and your email server (as shown in the previous code). Leave the fields empty if your ISP does not require them.

To verify that your settings are correct, launch the interactive shell and enterthe following:

>>> from django.core.mail import send_mail
>>> send_mail('Subject', 'Body of the message.',
'[email protected]',
['[email protected]'])

Replace [email protected] with your actual email address. If the above call to send_mail does not raise an exception and you receive the email, then all is set. Otherwise, you need to verify your settings with your ISP and try again.

Once the settings are correct, sending an email in Django is a piece of cake! We will use send_mail to send the invitation email. But first, let’s create a data model for storing invitations.

The invitation data model

An invitation consists of the following information:

  • Recipient name
  • Recipient email
  • The User object of the sender

We also need to store an activation code for the invitation. This code will be sent in the invitation email. The code will serve two purposes:

  • Before accepting the invitation, we can use the code to verify that the invitation actually exists in the database
  • After accepting the invitation, we can use the code to retrieve the invitation information from the database and create friendship relationships between the sender and the recipient

With this in mind, let’s create the Invitation data model. Open the bookmarks/models.py file and append the following code to it:

class Invitation(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField()
code = models.CharField(max_length=20)
sender = models.ForeignKey(User)

def __unicode__(self):
return u'%s, %s' % (self.sender.username, self.email)

There shouldn’t be anything new or difficult to understand in this model. We simply defined fields for the recipient name, recipient email, activation code, and the sender of the invitation. We also created a __unicode__ method for debugging, and enabled the model in the administration interface. Do not forget to run manage.py syncdb to create the new model’s table in the database.

Next, we will add a method for sending the invitation email. The method will use classes and methods from several packages. So, put the following import statements at the beginning of the bookmarks/models.py file, and append the send method to the Invitation data model in the same file:

from django.core.mail import send_mail
from django.template.loader import get_template
from django.template import Context
from django.conf import settings
class Invitation(models.Model):
[...]
def send(self):
subject = u'Invitation to join Django Bookmarks'
link = 'http://%s/friend/accept/%s/' % (
settings.SITE_HOST,
self.code
)
template = get_template('invitation_email.txt')
context = Context({
'name': self.name,
'link': link,
'sender': self.sender.username,
})
message = template.render(context)
send_mail(
subject, message,
settings.DEFAULT_FROM_EMAIL, [self.email]
)

The method works by loading a template called invitation_email.txt and passing the following variables to it: the name of the recipient, the activation link, and the sender username. The template is then used to render the body of the invitation email. After that, we used send_mail to send the email.

There are several observations to make here:

  • The format of the activation link is http://SITE_HOST/friend/accept/CODE/. We will write a view to handle such URLs later in this article.
  • This is the first time we use a template to render something other than a web page. As you can see, the template system is quite flexible and allows us to build emails as well as web pages, or any other text.
  • We used the get_template and render methods to build the message body as opposed to the usual render_to_response call. If you remember, this is how we rendered templates early in the book. We are doing this here because we are not rendering a web page.
  • The last parameter of send_mail is a list of recipient emails. Here we are passing only one email address. But if you want to send the same email to multiple users, you can pass all of the email addresses in one list to send_mail.

Since the send method loads a template called invitation_email.txt, create a file with this name in the templates folder and insert the following content into it:

Hi {{ name }},

{{ sender }} invited you to join Django Bookmarks,
a website where you can post and share your bookmarks with friends!

To accept the invitation, please click the link below:
{{ link }}

-- Django Bookmarks Team

Once we write the send method, our Invitation data model is ready. Next, we will create a form that allows users to send invitations.

LEAVE A REPLY

Please enter your comment!
Please enter your name here