gpt4 book ai didi

python - Django 完整性错误处理

转载 作者:行者123 更新时间:2023-12-01 04:52:07 26 4
gpt4 key购买 nike

我创建了一个用户注册网站,其中包含名字、姓氏、电话号码等。我已经成功建立了与 MySQL 数据库的连接。我需要有关 django 中 IntegrityError 处理的帮助,因为我是新手。当 2 个用户输入相同的电话号码时,django 会将我带到包含大量信息的调试页面。相反,我想立即通知用户,具有相同电话号码的另一个用户已经存在。请提供有关此的任何指示。以下是我处理表单的views.py 文件:

from django.shortcuts import render
from formProcessing.forms import UserForm




def form(request):
#This is using regular Django forms
#print request.POST
#form = EmailForm(request.POST or None)

#This is using model forms
form = UserForm(request.POST or None)
if form.is_valid():
new_instance = form.save(commit=True)

new_instance.save()
context = {"form": form }
template = "form.html"
return render(request,template,context)

最佳答案

在您的 UserForm 中,您可以覆盖 number 属性的 clean 方法,假设您的属性名为“number

class UserForm(ModelForm):
#your user form attributes and stuff


def clean_number(self, value):
user_number = value
number_occurrences = User.objects.filter(number=user_number).count()
if number_occurrences > 0:
raise forms.ValidationError("You number is already taken by other user")

return self.cleaned_data

查看有关 form validation 的 django 文档

如果您不想覆盖干净的方法并在您的 View 中执行它。你可以。 (不优雅)

def form(request):
#This is using regular Django forms
#print request.POST
#form = EmailForm(request.POST or None)

#This is using model forms
number = request.POST.get('telephone')
number_occurrences = User.objects.filter(number=user_number).count()
if number_occurrences > 0:
context = {'error':'Number already exist'}
return render(request,template,context)

form = UserForm(request.POST or None)
if form.is_valid():
new_instance = form.save(commit=True)

new_instance.save()
context = {"form": form }
template = "form.html"
return render(request,template,context)

关于python - Django 完整性错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28200372/

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