python - 我如何检查 Django 中存在的用户名和邮件
问题描述
我刚开始学习Django。我做了一个登记表。它的工作很好。但我无法检查此注册表单中是否存在用户名和邮件。如果我尝试使用相同的用户名注册,我会收到 (1062, "Duplicate entry 'asdasd' for key 'username'") 错误。(asdasd我的用户名..)
我该如何解决这个问题?
表格.py
from django import forms
class RegisterForm(forms.Form):
username = forms.CharField(required=True, max_length=20, label= "Kullanıcı Adı")
email = forms.EmailField(required=True, label="E-Mail")
password = forms.CharField(max_length=20, label= "Password", widget=forms.PasswordInput)
confirm = forms.CharField(max_length=20, label="RePassword",widget=forms.PasswordInput)
def clean(self):
username = self.cleaned_data.get("username")
email = self.cleaned_data.get("email")
password = self.cleaned_data.get("password")
confirm = self.cleaned_data.get("confirm")
if password and confirm and password != confirm:
raise forms.ValidationError("Passwords dont match")
values = {
"username" : username,
"email" : email,
"password" : password,
}
return values
视图.py
from django.shortcuts import render, redirect
from .forms import RegisterForm
from django.contrib import messages
from django.contrib.auth.models import User
from django.contrib.auth import login
def register(request):
form = RegisterForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data.get("username")
email = form.cleaned_data.get("email")
password = form.cleaned_data.get("password")
newUser = User(username=username)
newUser.email = email
newUser.set_password(password)
newUser.save()
login(request, newUser)
messages.success(request,"Successful on Register")
return redirect("index")
context = {
"form": form
}
return render(request, "register.html", context)
def loginUser(request):
return render(request, "login.html")
def logoutUser(request):
return render(request, "logout.html")
太感谢了!
解决方案
最直接的方法是将方法添加到表单类
def clean_email(self):
if User.objects.filter(username=username).exists():
raise forms.ValidationError("Username is not unique")
def clean_username(self):
if User.objects.filter(email=email).exists():
raise forms.ValidationError("Email is not unique")
推荐阅读
- c# - 如何将 csc 升级到最新的 roslyn 工具
- c++ - collect2.exe:错误:ld 返回 1 退出状态窗口 7 SE
- tensorflow - MNIST 分类器在非 MNIST 数字上失败
- r - 将动态 UI 保存到全局 R 工作区
- c++ - 使用模板分配器和对对向量进行排序的函数
- ssl - nginx 多个 proxy_pass 使用不同的 ssl 证书和子域到同一个域
- javascript - 如何使用 Firestore 在 Javascript 中实现评论功能
- google-cloud-firestore - 特殊字符在 Firestore 字符串中不起作用
- sql - 如何生成 oracle SQL XML 格式
- ios - 我希望我的三个 textView 具有相同的大小