Changing user email address
I would like to allow a user to change his email address. A user would change his email address, then a confirmation email with a link would be sent to that address, after the user clicked the link it would change his email address in the database.
I know there django-generic-confirmation deals with confirmations like this, but I would like to try and do it on my own.
To change an email, my code would be:
User.objects.get(username=username).update(email=request.POST['email'])
And to send an email to that address, I would have:
if 'Change Email' in request.POST.values():
from django.core.mail import send_mail
send_mail(
'Confirm email change',
'Click this **link** to confirm your change of email',
'from@example.com',
[request.POST['email']]
)
How would I delay the change of email in the db until only after the user has confir开发者_JS百科med his email? And how would i create a link that activates the email for this process? Thank you.
This is pretty simple. What you want to do is write an app with at least a model that looks like this;
class EmailChangeAuth(models.Model):
auth_key = models.CharField(max_length=42)
user = models.ForeignKey(User)
new_email = models.CharField(max_length=256)
Fill in the auth_key with a UUID4 and you can treat it like you would a slug field in your urlconf.
Then write a view that takes the auth_key, searches for that in the database, and changes the user's email to new_email. Delete the record when you're done.
For bonus points, add in an expiration on it, and occasionally clean out any records older than a day.
You might also want to think about a security question type system instead. As the main reason a lot of people might want to change their email is that the old one no longer exists. For example leaving a company, a mail host disappearing (thats way less common now) etc, etc, etc.
How would I delay the change of email in the db until only after the user has confirmed his email?
That seems silly. You wait until they confirm the email. Maybe that's not what you're really asking.
And how would i create a link that activates the email for this process?
That makes little sense. Presumably, you're asking how to fill in **link**
.
If so, that's what the Django reverse()
function is for.
Write a view function for this.
Pick a sensible URL path for the view function.
Use
reverse
to generate the complete URL that gets inserted into the email.
精彩评论