[Django]-Request Approvals by E-mail and process it Python + Django

2đź‘Ť

âś…

Basically this technique used in email verification. This is where you should look into.

Let’s say you have model, named request, which has field like username to identify the person who requested access, database name, well, everything. But it will also have two “password-like” fields which will be used to determine if request was declined or not.

class Request(models.Model):
    user = models.ForeignKey ...
    databasename = 
    date = 
    ...
    access_granted = models.BooleanField(default=False)
    deny_token = models.CharField()
    allow_token = models.CharField()

The point is to generate those tokens on saving request in the View:

if request.method == POST:
    form = RequestForm(request.POST)
    if form.is_valid():
        data['user'] = form.cleaned_data['user'])
        data['databasename'] = form.cleaned_data['databasename'])
        ...
        data['access_token'] = GENERATE_USING_HASH_FUNCTION()
        data['deny_token'] = GENERATE_USING_HASH_FUNCTION()

        form.save(data)

Then you can use module EmailMultiAlternatives to send html email like so:

subject, from_email, to = 'Request', 'admin@example.com', form.cleaned_data['manager_email']
html_content = render_to_string(HTML_TEMPLATE, CONTEXT) # Just as any regular templates
text_content = strip_tags(html_content)

msg = EmailMultiAlternatives(subject, text_content, from_email, [to], reply_to=["admin@example.com"])
msg.attach_alternative(html_content, "text/html")
msg.send()

And inside that template you construct reverse url:

{% url 'app:grant_access' allow_token=token %} # "token" you get from context
{% url 'app:deny_access' deny_token=token %} # will become example.com/deny_access/7ea3c95, where 7ea3c95 is token

Then add lines to urls.py of your app like that:

url(r'^allow_access/(?P<allow_token>[0-9]+)$', CheckAcessView.as_view(), name="app:grant_access"),
url(r'^deny_access/(?P<deny_token>[0-9]+)$', CheckAcessView.as_view(), name="app:deny_access"),]

Then create CheckAcessView view. Where you access request stored in your database and check if, for example, parameter of url “allow_token” is equal stored allow_token. If so, change request status to allowed.

👤Coykto

Leave a comment