django表单跳过模型验证?

时间:2011-10-24 16:34:28

标签: django django-models django-forms

最近我下载了Pinax项目0.7以了解我可以应用于我自己的项目。特别是,我运行了Pinax并查看了Pinax应用于自己的书签应用程序。我将Bookmark应用程序及其依赖项复制到我自己的应用程序中。但是,Pinax在Django 1.0.4上运行,而我的是1.2.4,并且在表单验证中存在一些错误。以下是书签应用程序的片段:

class BookmarkInstance(models.Model):

    bookmark = models.ForeignKey(Bookmark, related_name="saved_instances", verbose_name=_('bookmark'))
    user = models.ForeignKey(User, related_name="saved_bookmarks", verbose_name=_('user'))
    saved = models.DateTimeField(_('saved'), default=datetime.now)

    description = models.CharField(_('description'), max_length=100)
    note = models.TextField(_('note'), blank=True)

    tags = TagField()

形式:

class BookmarkInstanceForm(forms.ModelForm):

    url = forms.URLField(label = "URL", verify_exists=True, widget=forms.TextInput(attrs={"size": 40}))
    description = forms.CharField(max_length=100, widget=forms.TextInput(attrs={"size": 40}))
    redirect = forms.BooleanField(label="Redirect", required=False)
    tags = TagField(label="Tags", required=False)

    def __init__(self, user=None, *args, **kwargs):
        self.user = user
        super(BookmarkInstanceForm, self).__init__(*args, **kwargs)
        # hack to order fields
        self.fields.keyOrder = ['url', 'description', 'note', 'tags', 'redirect']

    def clean(self):
        if 'url' not in self.cleaned_data:
            return
        if BookmarkInstance.objects.filter(bookmark__url=self.cleaned_data['url'], user=self.user).count() > 0:
            raise forms.ValidationError(_("You have already bookmarked this link."))
        return self.cleaned_data


    def save(self, commit=True):
        self.instance.url = self.cleaned_data['url']
        return super(BookmarkInstanceForm, self).save(commit)

    class Meta:
        model = BookmarkInstance

传入的参数是(<QueryDict: {u'url': [u'amazon.com'], u'note': [u'foo'], u'description': [u'bar'], u'tags': [u'']}>,),但在1.0.4中没有导致模型验证错误。那么,我如何在我的视图中进行最小的调整,可能跳过模型验证以适应这种差异?

0 个答案:

没有答案