v1.2.1 中的 Django 表单验证
我在我的一个项目中使用 django-bookmarks,最近更新到 Django 1.2.1。我注意到自更新以来表单提交未验证。请注意,我确实确认这适用于 Django v1.1.1,因此新版本和表单字段验证是不同的。
这是 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 中那样自动传入吗?
I'm using django-bookmarks for one of my projects and recently updated to Django 1.2.1. I noticed that the form submit does not validate since the update. Please note that I did confirm this is working with Django v1.1.1, so the new version and form field validation is different.
This is the model that forms.py is building off of:
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)
The view handling the 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
...
And the 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')
Using pdb, I saw that the foreign key values for BookmarkInstance were empty, therefor is_valid() would return false since all the fields didn't validate.
Does the init function need to be modified to pass in the foreign key parameters explicitly? Shouldn't the foreign key values be passed in automatically like it was doing in v1.1.1?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上我刚刚解决了这个问题,而且非常简单。只需取消注释:,
因为它需要明确说明字段。这适用于 Django v1.1.1,我猜想新的表单验证需要在 v1.2.1 中明确说明。
I actually just solved it and it was embarrassingly easy. Just uncomment the:
as it needs the fields to be explicitly stated. This worked with Django v1.1.1 and I guess the new form validation needs it explicitly stated in v1.2.1.