Change user email in Django without using django-profiles
In my Django application I would like the user to be able to change the email address. I've seen solution of StackO开发者_如何学运维verflow pointing people to django-profiles. Unfortunately I don't want to use a full fledged profile module to accomplish a tiny feat of changing the users email. Has anyone seen this implemented anywhere. The email address verification procedure by sending a confirmation email is a requisite in this scenario.
I've spent a great a deal of time trying to a find a solution that works but to no avail.
Cheers.
The email address belongs to the user model, so there's no need to use profiles to let users update their email. Create a model form from the user model that has only email as a field, then provide that form in your view and process it. Something like:
class UserInfoForm(forms.ModelForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ('email',)
def my_view(request):
if request.POST:
user_form = UserInfoForm(request.POST, instance=request.user)
if user_form.is_valid():
user_form.save()
return HttpResponseRedirect(reverse('form_success_screen'))
else:
user_form = UserInfoForm()
return render_to_response('my-template.html', {'user_form': user_form}, context_instance=RequestContext(request))
Note that if the form is successful, I'm returning a HttpResponseRedirect to send the user to another page. In this case, I'm looking up a named url from my urls file.
Seems that someone did write their own. It allows users to change their email addresses and sends confirmation emails.
django-emailchange
Not quite sure if it's a new requirement of Django 1.4 but I tried Tom's suggestion:
class UserInfoForm(forms.ModelForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ('email')
and got a fields error. You must have a trailing comma after each field (or so that's what solved my error):
fields = ('email',)
fixed the problem
精彩评论