2010-07-02 68 views
0

我爲我的一個項目使用了django書籤,並且最近更新到了Django 1.2.1。我注意到表單提交自更新以後不驗證。請注意,我確認這是與Django v1.1.1一起工作,所以新版本和表單字段驗證是不同的。v1.2.1中的Django表單驗證

這是的forms.py正在建設關的模式:

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) 

處理POST的觀點:

if request.method == "POST": 
    bookmark_form = BookmarkInstanceForm(request.user, request.POST) 
    if bookmark_form.is_valid(): 
     bookmark_instance = bookmark_form.save(commit=False) 
     bookmark_instance.user = request.user 
     bookmark_instance.save() 
     bookmark = bookmark_instance.bookmark 
     ... 

而且forms.py:

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', '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 
     #fields = ('url', 'description', 'note', 'redirect') 

使用pdb,我看到BookmarkInstance的外鍵值爲空,因此is_valid()將返回false,因爲所有字段沒有驗證。

init函數是否需要修改以顯式傳遞外鍵參數?不應該像V1.1.1中那樣自動傳入外鍵值?

回答

0

我剛剛解決了它,這是令人尷尬的容易。只需取消註釋:

#fields = ('url', 'description', 'note', 'redirect') 

因爲它需要明確聲明的字段。這與Django v1.1.1一起工作,我猜想新的表單驗證需要在v1.2.1中明確聲明。