gpt4 book ai didi

python - 我如何检查 Django 中是否存在用户名和电子邮件

转载 作者:行者123 更新时间:2023-12-02 17:03:07 25 4
gpt4 key购买 nike

我刚开始学习 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

View .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_username(self):
if User.objects.filter(username=username).exists():
raise forms.ValidationError("Username is not unique")

def clean_email(self):
if User.objects.filter(email=email).exists():
raise forms.ValidationError("Email is not unique")

关于python - 我如何检查 Django 中是否存在用户名和电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53115349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com