[Django]-Django confirm email. Change value from false to true

3👍

You can do something like this

Model

import random
import string

class Meeting(models.Model):
    name = models.CharField(max_length=255)
    time = models.DateTimeField()
    confirmed = models.BooleanField(default=False)
    key = models.CharField(max_length=32) 

    def save(self, *args, **kwargs):
        '''
        On save generate key which will be sent in email
        '''
        self.key = ''.join(random.choice(string.letters) for i in xrange(32))
        super(Meeting, self).save(*args, **kwargs)
        return self

views.py

def confirm(request, key):
    try:
        meeting = Meeting.objects.get(key=key)
    except Meeting.DoesNotExist:
        # wrong key, do something, redirect to somewhere etc
        template = 'error.html'
    else:
        meeting.confirmed = True
        meeting.save()
        template = 'success.html'
    render(request, template)

def send_email(request):
    email = request.user.email
    meeting = Meeting.objects.get(...your condition here...)
    send_mail('Confirmation email',
              # this is a link you wanted to
              '<a href="%s">confirm</a>' % reverse('user_confirm',
                                                   kwargs={'key': meeting.key}),
              'from@youremail.com', [email])
    render(request, 'mailsent.html')

urls.py

urlpatterns = patterns('',
    url(r'^confirm/(?P<key>[\w]{32})/$', 'yourapp.views.confirm',
        name='user_confirm'),
    )

Leave a comment