如何在 Django 中注册和编辑用户时正确验证电子邮件

how to validate email properly while register and edit users in django

我没有使用 django 默认管理仪表板,我正在为 admin.but 使用我自己的自定义模板我在编辑和更新 user.I 时遇到了一些问题想为每个用户发送电子邮件在数据库中独一无二 我的 forms.py 中的这段代码在添加用户时表现很好,但在更新它时我遇到了一些关于 email.Since 的问题 我已经完成了 forms.py 中独一无二的电子邮件它正在提供我在更新时出错 also.How 我可以更新用户以便编辑的用户可以拥有相同的电子邮件但与其他用户的电子邮件地址不同。

forms.py

class RegisterForm(UserCreationForm):
    def clean_email(self):
        email = self.cleaned_data['email']
        if User.objects.filter(email=email).exists():
            raise ValidationError('Email Already Exists')
        return email

    class Meta:
        model = User
        fields = ['username', "email", "password1", "password2",'is_superuser','is_staff','is_active']

views.py

def register(request):

if not request.user.is_superuser:
    messages.warning(request, 'Permission Denied.You have no permission to register users.')
    return redirect('students:home')
if request.method == "POST":
    form = RegisterForm(request.POST)
    if form.is_valid():
        user = form.save(commit=False)
        user.save()
        messages.success(request,'user created with username {}'.format(user.username))
        return redirect('students:our_users')
else:
    form =RegisterForm()
return render(request,'students/register.html',{'form':form})

def editusers(request,id):
    if not request.user.is_superuser:
        messages.warning(request, 'Permission Denied.You have no permission to perform this action.')
        return redirect('students:our_users')
    user = User.objects.get(id=id)
    return render(request,'students/edit_users.html',{'user':user})


def updateusers(request,id):
    if not request.user.is_superuser:
        messages.warning(request, 'Permission Denied.You have no permission to perform this action.')
        return redirect('students:our_users')
    user = User.objects.get(id=id)
    form = RegisterForm(request.POST,instance=user)
    if form.is_valid():
        user = form.save(commit=True)
        user.save()
        messages.success(request,'{} updated'.format(user.username))
        return redirect('students:our_users')
    else:
        messages.error(request,'Error in Form')
        return redirect('students:edit_user',user.id)

register template

    <form action="" method="post">
                      {% csrf_token %}
                        {% bootstrap_form form %}
                        <div class="text-xs-right">
                            <button type="submit" class="btn btn-info">Add</button>
                        </div>
                    </form>

edituser template

<form action="{% url 'students:update_user' user.id %}" method="post">
                    {% csrf_token %}

<div class="form-group"><label for="id_username">Username</label><input type="text" name="username" maxlength="150" autofocus class="form-control" value="{{user.username}}" placeholder="Username" title="Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only." required id="id_username">


    <small class="form-text text-muted">Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.</small>

</div>
<div class="form-group"><label for="id_email">Email</label><input type="email" name="email" value="{{user.email}}" class="form-control" placeholder="Email" title="" required id="id_email"></div>
<div class="form-group"><label for="id_password1">Password</label><input type="password" name="password1" value="{{user.password}}" class="form-control" placeholder="Password" title="Your password must contain at least 8 characters.Your password can&amp;#39;t be entirely numeric." required id="id_password1">


    <small class="form-text text-muted"><ul><li>Your password must contain at least 8 characters.</li><li>Your password can&#39;t be entirely numeric.</li></ul></small>

</div>
<div class="form-group"><label for="id_password2">Password confirmation</label><input type="password" name="password2" value="{{user.password}}" class="form-control" placeholder="Password confirmation" title="Enter the same password as before, for verification." required id="id_password2">


    <small class="form-text text-muted">Enter the same password as before, for verification.</small>

</div>
<div class="form-group"><div class="form-check"><input type="checkbox" name="is_superuser" {% if user.is_superuser %}checked="checked" {% endif %}
                                                       class="form-check-input" id="id_is_superuser"><label class="form-check-label" for="id_is_superuser" title="Designates that this user has all permissions without explicitly assigning them.">Admin status</label>


    <small class="form-text text-muted">Designates that this user has all permissions without explicitly assigning them.</small>

</div></div>
                    <div class="form-group"><div class="form-check"><input type="checkbox" name="is_staff" {% if user.is_staff %}checked="checked" {% endif %} class="form-check-input" id="id_is_staff"><label class="form-check-label" for="id_is_staff" title="Designates whether the user can log into this admin site.">Staff status</label>


    <small class="form-text text-muted">Designates whether the user can log into this admin site.</small>

</div></div>
<div class="form-group"><div class="form-check"><input type="checkbox" {% if user.is_active %}checked="checked" {% endif %} name="is_active"  class="form-check-input" id="id_is_active"><label class="form-check-label" for="id_is_active" title="Designates whether this user should be treated as active. Unselect this instead of deleting accounts.">Active</label>


    <small class="form-text text-muted">Designates whether this user should be treated as active. Unselect this instead of deleting accounts.</small>

</div></div>


                    <div class="text-xs-right">
                        <button type="submit" class="btn btn-info">Update</button>
                    </div>
                </form>

你可以这样做:

def clean_email(self):
    email = self.cleaned_data['email']
    if self.instance and self.instance.pk:
         return email
    else User.objects.filter(email=email).exists():
        raise ValidationError('Email Already Exists')
    return email

我在这里检查表单是否有任何实例以及该实例是否有任何主键。当您从视图中传递此实例属性时,它会在表单中设置,例如在您的代码中:form = RegisterForm(request.POST,instance=user).