在Django中保存表单数据之前进行重复检查 [英] Duplication check before saving the form data in Django
问题描述
我得到的表格如下:
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方法来检查此课程是否已存在于数据库中.这对我来说很好.
As you can see I overwrote the clean method to check whether this course has already existed in the database when the user is trying to add it. This works fine for me.
但是,当我想为表单添加相同的检查以进行编辑时,出现了问题.由于正在编辑,因此具有相同课程名称的记录已存在于数据库中.因此,相同的检查会在课程名称已经存在的情况下引发错误.但是我需要检查重复项,以避免用户将课程名称更新为另一个已经存在的课程名称.
However, when I want to add the same check for the form for editing, the problem happened. Because it is editing, so the record with same course name has already exist in the DB. Thus, the same check would throw error the course name has already exist. But I need to check the duplication in order to avoid the user updating the course name to another already existed course name.
我正在考虑检查课程名称的值以查看其是否更改.如果已更改,则可以执行与上述相同的检查.如果尚未更改,则无需进行检查.但是我不知道如何获取原始数据进行编辑.
I am thinking of checking the value of the course name to see if it is changed. If it has been changed, than I can do the same check as above. If it has not been changed, I don't need to do the check. But I don't know how can I obtain the origin data for editing.
有人知道如何在Django中执行此操作吗?
Does anyone know how to do this in 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
并让框架为您处理该验证.
I think you should just set unique=True
on the Course.name
field and let the framework handle that validation for you.
更新:
由于 unique = True
不是适合您的情况的正确答案,因此您可以通过以下方式进行检查:
Since unique=True
is not the right answer for your case, you can check this way:
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
.
As a side note, I've also changed your custom error handling to use a more standard ValidationError
.
这篇关于在Django中保存表单数据之前进行重复检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!