django-selectable表单验证和模型表单过滤器查询集

时间:2016-01-30 10:32:32

标签: django python-2.7 django-models django-forms

我使用django-selectable进行自动整理,我需要模型表格验证

所以我在forms.py

中进行了验证
def clean(self):
    cl_title = Color.objects.values_list('title',flat=True)
    if self.cleaned_data.get('color') != cl_title:
        raise forms.ValidationError('this color is not found in the database')
    return self.cleaned_data

我生成错误

 Request Method:    POST
 Exception Type:    ValueError
 Exception Value: Cannot assign "<Color: awffawfwa>": "Color" instance isn't saved in the database.

它不起作用 见下面的详细信息

models.py

class Color(models.Model):
    title = models.CharField('color title', max_length=100)
    user = models.CharField(User)
    description = models.TextField('description')

    def __str__(self):
        return self.title

class Item(models.Model):
    user = models.ForeignKey(User)
    color = models.ForeignKey(Color)
    # ... some logic

    def __str__(self):
        return self.color.title

lookups.py

from selectable.base import ModelLookup
from selectable.registry import registry
from .models import Color

class ColorLookup(ModelLookup):
    model = Book
    search_fields = ('title__icontains',)

registry.register(ColorLookup)

forms.py

from django import forms
from .models import Color
import selectable.forms as selectable
from .lookups import BookLookup

class ItemSelectForm(forms.ModelForm):
    color = selectable.AutoCompleteSelectField(
    lookup_class = ColorLookup,
    allow_new = True,
    label= 'select',
    required = True,
)

class Meta:
    model = Color
    fields = ('color',)

def clean(self):
    cl_title = Color.objects.values_list('title',flat=True)
    if self.cleaned_data.get('color') != cl_title:
        raise forms.ValidationError('this color is not found in the database')
    return self.cleaned_data

但它不起作用,你可以帮助我,如何纠正这个错误? 提前谢谢;)

1 个答案:

答案 0 :(得分:1)

values_list将返回一个颜色列表,因此您的单个值永远不会等于此数组,您需要检查此列表中的颜色(如果它确实是您需要的列表..)

您还可以将此逻辑分离为单独的清洁颜色方法。

def clean_color(self):
    color = self.cleaned_data.get('color')
    cl_title = Color.objects.values_list('title',flat=True)
    if color not in cl_title:
        raise forms.ValidationError('this color is not found in the database')
    return color  

或者也许首选,你可以做

if not Color.objects.filter(title=color).exists():

这是一个更有效的查询,因为它不会从数据库中返回任何不需要的值。