Reputation: 1277
I was testing my registration view and i noticed that if i try to register using an alreaxy existing Username, i'll get an error; if i try to register using an already existing email, the app will let me do so.
Obviously, i don't want someone to register multiple accounts with the same email on my site. I'm fairly new to Django, and since i noticed that the form checked if an username already exists, i thought it would do the same with the email field.
I don't really know how to go from that, should i work on my view or on the form? And how can i make it loop through my DB and find if an e-mail had already been registered? I thought email = form.cleaned_data.get('email')
would do the trick, but it didn't.
Any help is appreciated.
Here is my view:
def register(request):
if request.method == "POST":
form = NewUserForm(request.POST)
if form.is_valid():
user = form.save()
username = form.cleaned_data.get('username')
email = form.cleaned_data.get('email')
messages.success(request, f"New Account Created: {username}")
login(request, user)
messages.info(request, f"You are now logged in as {username}")
return redirect("main:homepage")
else:
for msg in form.error_messages:
messages.error(request, f"{msg}: {form.error_messages[msg]}")
form = NewUserForm
return render(request,
"main/register.html",
context={"form":form})
And here is the form:
class NewUserForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ("username", "email", "password1", "password2")
def save(self, commit=True):
user = super(NewUserForm, self).save(commit=False)
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
Upvotes: 0
Views: 81
Reputation: 1398
Compare the email address provided with email address in User model .
if form.is_valid():
user = form.save()
username = form.cleaned_data.get('username')
email = form.cleaned_data.get('email')
if User.objects.filter(email__exact=email).count() == 0:
messages.success(request, f"New Account Created: {username}")
login(request, user)
messages.info(request, f"You are now logged in as {username}")
return redirect("main:homepage")
else:
return HttpResponse('This email address is already registered ')
Upvotes: 1
Reputation: 112
I think the best alternative is to program your own user model, this will allow you to add a unique restriction on email, You can take a look at the documentation
Upvotes: 0