gpt4 book ai didi

django - 在 Django 中保存表单数据之前的重复检查

转载 作者:行者123 更新时间:2023-12-01 07:46:35 24 4
gpt4 key购买 nike

我得到如下表格:

class CourseAddForm(forms.ModelForm):
"""Add a new course"""
name = forms.CharField(label=_("Course Name"), max_length=100)
description = forms.Textarea()
course_no = forms.CharField(label=_("course Number"), max_length=15)


#Attach a form helper to this class
helper = FormHelper()
helper.form_id = "addcourse"
helper.form_class = "course"

#Add in a submit and reset button
submit = Submit("Add", "Add New Record")
helper.add_input(submit)
reset = Reset("Reset", "Reset")
helper.add_input(reset)

def clean(self):
"""
Override the default clean method to check whether this course has been already inputted.
"""
cleaned_data = self.cleaned_data
name = cleaned_data.get('name')
hic = cleaned_data.get('course_no')

try:
course=Course.objects.get(name=name)
except Course.DoesNotExist:
course=None

if course:
msg = u"Course name: %s has already exist." % name
self._errors['name'] = self.error_class([msg])
del cleaned_data['name']
return cleaned_data
else:
return self.cleaned_data

class Meta:
model = Course

如您所见,我重写了 clean 方法,以在用户尝试添加该类(class)时检查该类(class)是否已存在于数据库中。这对我来说很好。

但是,当我想为编辑表单添加相同的检查时,问题发生了。因为是编辑,所以数据库中已经存在同名类(class)的记录。因此,相同的检查会抛出类(class)名称已经存在的错误。但是我需要检查重复项以避免用户将类(class)名称更新为另一个已经存在的类(class)名称。

我正在考虑检查类(class)名称的值以查看它是否已更改。如果它已更改,那么我可以进行与上述相同的检查。如果它没有改变,我不需要做检查。但我不知道如何获取原始数据进行编辑。

有谁知道如何在 Django 中执行此操作?

我的观点如下:

@login_required
@csrf_protect
@never_cache
@custom_permission_required('records.change_course', 'course')
def edit_course(request,course_id):
# See if the family exists:
try:
course = Course.objects.get(id=course_id)
except Course.DoesNotExist:
course = None

if course:
if request.method == 'GET':
form = CourseEditForm(instance=course)
return render_to_response('records/add.html',
{'form': form},
context_instance=RequestContext(request)
)
elif request.method == 'POST':
form = CourseEditForm(request.POST, instance=course)
if form.is_valid():
form.save()
return HttpResponseRedirect('/records/')
# form is not valid:
else:
error_message = "Please correct all values marked in red."
return render_to_response('records/edit.html',
{'form': form, 'error_message': error_message},
context_instance=RequestContext(request)
)
else:
error = "Course %s does not exist. Press the 'BACK' button on your browser." % (course)
return HttpResponseRedirect(reverse('DigitalRecords.views.error', args=(error,)))

谢谢。

最佳答案

我认为您应该在 Course.name 字段上设置 unique=True 并让框架为您处理验证。

更新:

由于 unique=True 不是您的案例的正确答案,您可以这样检查:

def clean(self):
"""
Override the default clean method to check whether this course has
been already inputted.
"""
cleaned_data = self.cleaned_data
name = cleaned_data.get('name')

matching_courses = Course.objects.filter(name=name)
if self.instance:
matching_courses = matching_courses.exclude(pk=self.instance.pk)
if matching_courses.exists():
msg = u"Course name: %s has already exist." % name
raise ValidationError(msg)
else:
return self.cleaned_data

class Meta:
model = Course

作为旁注,我还更改了您的自定义错误处理以使用更标准的 ValidationError

关于django - 在 Django 中保存表单数据之前的重复检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12960906/

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