错误的电子邮件被保存在Django的数据库中

mpbci0fu  于 2023-04-13  发布在  Go
关注(0)|答案(1)|浏览(95)

我正在做一个项目,用户必须先注册才能使用这个应用程序。我附上了下面的注册代码。
views.py

# Create your views here.
def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST) # post request is gonna contain data in the message body and validate that form data
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'Account created for {username}. You are now able to log in.')
            return redirect('login')
    else:
        form = UserRegisterForm() # display a blank form
    return render(request, 'users/signup.html', {'form': form})
{% extends 'users/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container">
    <section id="formHolder">
        <div class="row">
            <!-- Brand Box -->
            <div class="col-sm-6 brand">
                <a href="#" class="logo">Bookstagram <span>.</span></a>
                <div class="heading">
                    <h3>Bookstagram</h3>
                    <p>Show Off Your Bookish Aestheics</p>
                </div>
            </div>
            
            <!-- Form Box -->
            <div class="col-sm-6 form">
                <!-- Signup Form -->
                <div class="login form-peice">
                    <form class="login-form" method="POST">
                        {% csrf_token %}
                        <fieldset class="form-group">
                            {{ form|crispy }}
                        </fieldset>
                        <div class="CTA">
                            <input type="submit" value="Signup Now" id="submit">
                            <a href="{% url 'login' %}">I have an account</a>
                        </div>
                    </form>
                </div><!-- End Signup Form -->
            </div>
        </div>
    </section>
</div>
{% endblock content %}

如果我给予了一个错误的电子邮件,如“cindrella@gmail.c”或“cindrella@g.com”,系统会将用户详细信息保存在数据库中,然后他可以使用该凭据登录。但是电子邮件不正确。那么,我如何使用正确的电子邮件注册?如果电子邮件错误,系统应该显示不正确的电子邮件。因此,用户详细信息将不会存储在数据库中。

tcomlyy6

tcomlyy61#

你可以使用django内置的'EmailValidator'来检查邮件域,如下所示。这里是docs来获取更多信息。

#form.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.core.validators import EmailValidator
from django.core.exceptions import ValidationError

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField(validators=[EmailValidator()])

    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

    def clean_email(self):
        email = self.cleaned_data.get('email')

        # Check if the email is valid
        email_validator = EmailValidator()
        try:
            email_validator(email)
        except ValidationError:
            raise ValidationError('Invalid email.')

        # Check if the email domain is allowed
        allowed_domains = ['gmail.com', 'yahoo.com', 'hotmail.com']
        email_domain = email.split('@')[-1]
        if email_domain not in allowed_domains:
            raise ValidationError(f'Email domain must be one of the following: {", ".join(allowed_domains)}.')

        return email

相关问题