Recently, one of our clients wanted to restrict signups on their platform to a list of whitelisted email addresses. This was urgent, I didn't have the time to build a form to upload the csv files. Ideally, what I would have done was have one of our frontend devs
- build a form on the admin dashboard
- I create a model and an endpoint for uploading the files
- Use celery to process handle to data import especially if the file contains a lot of emails. Thank goodness this had just 700+ emails
- We connect test, and voila
But we didn't have the luxury of this as we were seriously trying to beat another deadline.
So here is how I hacked it in 15 - 20 mins and went back to other important things.
First thing was to create model, then add the csv file to the project's root dir and finally run a small function that imports the data into the model.
I make use of django-extensions
which provides a more powerful django shell. You should check it out.
#models.py
class Whitelist(models.Model):
"""
A list of whitelisted email addresses that are allowed to signup
"""
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
email = models.EmailField(unique=True)
def __str__(self):
return self.email
Run migrations after this
To import the data, follow these commands
./manage.py shell_plus
import csv
with open('whitelist.csv', 'r') as cv:
emails = csv.reader(cv, delimiter=' ')
for email in emails:
Whitelist.objects.create(email=email)
This will import the data into the whitelist.
I will write another post on how I handled the registration part where only whitelisted emails were allowed to register (maybe I should build a small package to handle this). But if you want to go ahead just incase I never put up that post, the trick is to have a custom registration serializer and add a check for email addresses before a registration can be completed.