Radial
Radial

Reputation: 373

How and where to call a method in a Class based view Django

As part of a News Years resolution, I have promised to myself that I would learn to write Class Based Views, but as it turns out, I need some help..

What I am trying to do is call a method that generates a random number and then sends an email before the page loads, which I comfortable doing (I'll probably use celery to send the mail in the background).

What I don't understand is how and where to call the methods random_code() and send_email() (see below)?

Do I do this by overriding setup(), dispatch() or get() etc?

Can someone please give me a basic example of what to do?

The class is going to look something like this:

class VerifyCode(FormView):

    template_name = "account/verify.html"
    form_class = VerifyForm

    def random_code(self):
        #random_code generator
        return random_code

    def send_email(self):
        #code to send email

Many thanks in advance.

Upvotes: 1

Views: 651

Answers (1)

NixonSparrow
NixonSparrow

Reputation: 6378

It depends on which REST method do you want to call it. If you are using simple GET, then call it in get() like this:

class VerifyCode(FormView):

    template_name = "account/verify.html"
    form_class = VerifyForm

    def random_code(self):
        #random_code generator
        return random_code

    def send_email(self):
        #code to send email

    def get(self, request, *args, **kwargs):
        ...
        self.random_code()
        self.send_email()
        return super().get(request, *args, **kwargs)

In similar way in post() for POST method.

Another thing is you can send emails directly with Django. I do that and it's pretty simple. Check this DOCS. You can post another question about that if you have something.

Upvotes: 1

Related Questions