ModelChoiceField上的验证错误

时间:2014-04-05 20:32:53

标签: django forms validation django-errors

我的django formset中有验证错误。从数据库填充的两个下拉列表没有通过验证,我不明白我的错误。

enter image description here

模型

class Country(models.Model):
    country_code=models.CharField(max_length=2, primary_key=True)
    country=models.CharField(max_length=20, unique=True)

    def __unicode__(self):
        return u"%s" % self.country

class Status(models.Model):
    verbatim = models.ForeignKey(Verbatim)
    country = models.ForeignKey(Country)
    status = models.CharField(max_length=5, db_index=True)

    def __unicode__(self):
        return u"%s" % self.status

    class Meta:
        unique_together=(("verbatim", "country"), )

class ImportMinAttend(models.Model):
    country=models.CharField(max_length=2, blank=False, null=False)
    verbatim=models.CharField(max_length=250, blank=False, null=False)
    status=models.CharField(max_length=5, blank=True, null=True, default=None)

形式

class MinAttendForm(forms.ModelForm):
    country=forms.ModelChoiceField(queryset=Country.objects.all(), empty_label="Select a country")
    status=forms.ModelChoiceField(queryset=Status.objects.values_list('status', flat = True).distinct(), empty_label="Select a status")
    class Meta:
        model=ImportMinAttend
        #fields used for the validation
        fields = ('country', 'verbatim', 'status')

查看

class MinAttendUpdate(UpdateView):
    model = ImportMinAttend
    fields = ['country', 'verbatim', 'status']
    form_class=MinAttendForm

    def post(self, request, *args, **kwargs):
        ...
        MinAttendFormSet = modelformset_factory(self.model, form=self.form_class, fields=self.fields, extra=len(attendances), max_num=len(attendances)+self.nb_extra_forms)
        formset=MinAttendFormSet(request.POST, queryset=attendances)
        ...

第一个国家的源代码选择:

<select name="form-0-country" id="id_form-0-country">
<option value="">Select a country</option>
<option value="AT" selected="selected">Austria</option>
<option value="BE">Belgium</option>
<option value="BG">Bulgaria</option>
...

第一个状态选择的源代码:

<select name="form-0-status" id="id_form-0-status">
<option value="">Select a status</option>
<option value="AB">AB</option>
<option value="CS">CS</option>
<option value="M" selected="selected">M</option>
</select> 

关于国家/地区选择:显示的值超过两个字符,但使用的密钥恰好有2个字符。为什么这个验证错误? 关于状态,我甚至不理解这个问题...

非常感谢。

编辑:已解决:

我找到了“脏”的解决方法。 对于国家选择,我使用select的键,而不是值:

def clean_country(self):
        data = self.cleaned_data['country'].pk
        return data

对于状态选择,如果选择了值,则删除验证错误:

 def clean(self):
        #call status clean method
        self.cleaned_data["status"]=self.clean_status()
        return self.cleaned_data

 def clean_status(self):
        #valid if a value has been selected
        if self["status"].value()!="":
            del self._errors["status"]
        return self["status"].value()

它有效,但为什么我必须这样做? :(

1 个答案:

答案 0 :(得分:1)

我认为你这样做很难。利用ModelForm,有更简单的方法。这是一个完整的例子。阅读它并使其适应您的模型:

from django.db import models
from django.forms import ModelForm

TITLE_CHOICES = (
    ('MR', 'Mr.'),
    ('MRS', 'Mrs.'),
    ('MS', 'Ms.'),
)

class Author(models.Model):
    name = models.CharField(max_length=100)
    title = models.CharField(max_length=3, choices=TITLE_CHOICES)
    birth_date = models.DateField(blank=True, null=True)

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Book(models.Model):
    name = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)

class AuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ['name', 'title', 'birth_date']

class BookForm(ModelForm):
    class Meta:
        model = Book
        fields = ['name', 'authors']