检查Django中数据库中是否存在值

时间:2017-09-07 12:22:18

标签: python django validation

我有一个类别字段category_name unique,我在从django admin提交表单后验证该字段的表单值。

admin.py -

from django.core.exceptions import ValidationError

class categoryAdmin(admin.ModelAdmin):

 list_display = ('category_name','module_name')

 def add_view(self, request, extra_content=None):
        self.form = CategoryUploadForm
        return super(categoryAdmin, self).add_view(request)

 def change_view(self, request, object_id, extra_content=None):
        self.form = CategoryManageForm
        return super(categoryAdmin, self).change_view(request, object_id)

 def save_model(self, request, obj, form, change):

   if not change:
            category_name, module_names = \
                self.handle_uploaded_file(request.FILES['category_file'])
   else:
            category_name = request.POST['category_name']
            module_names = request.POST['module_name']

   if category_name and Category.objects.filter(category_name=category_name).exists():
            raise forms.ValidationError('This category is already in the database. Please supply a different category.')
   return category_name

错误是 -

ValidationError at /admin/accounts/category/add/
['This category is already in the database. Please supply a different category.']

非常感谢任何帮助。提前谢谢。

1 个答案:

答案 0 :(得分:0)

你根本不应该这样做。如果category_name需要是唯一的,则在模型中的字段上设置{% for department in departments %} {% for task in department.tasksOrderedByDueDate %} ... {% endfor %} {% endfor %} 属性。

更一般地说,验证检查属于表单或模型,而不属于管理类。