在一个ValidationError中提高FormView并将它传递给带有重新加载表单的模板的正确方法是什么?目前,我有以下几点:
class ProfileUpdateView(FormView):
template_name = 'profile_update.html'
form_class = UserDetailForm
success_url = '/profile/'
def form_valid(self, form):
userdetail = form.save(commit = False)
try:
already_exist_info = UserDetail.objects.get(document_type=userdetail.document_type,
series=userdetail.series, number=userdetail.number)
raise forms.ValidationError("Document already exists in DB")
except UserDetail.DoesNotExist:
[... some stuff here ...]
userdetail.save()
return super(ProfileUpdateView, self).form_valid(form)它可以工作,我得到了错误页面,但我更喜欢在模板中显示错误,并重新加载表单。此外,是否有一种内置的方式来获取ValidationError in FormView?我的意思是,不从django进口django。
谢谢。
编辑
好吧,我决定用其他的方式来完成所有的技巧--使用clear()方法。所以现在我有了这个:
views.py
class ProfileUpdateView(FormView):
template_name = 'profile_update.html'
form_class = UserDetailForm
success_url = '/profile/'
def form_valid(self, form):
userdetail = form.save(commit = False)
#[... some stuff ...]
userdetail.save()
return super(ProfileUpdateView, self).form_valid(form)forms.py
class UserDetailForm(forms.ModelForm):
class Meta:
model = UserDetail
exclude = ('user', )
def clean(self):
cleaned_data = super(UserDetailForm, self).clean()
document_type = cleaned_data.get("document_type")
series = cleaned_data.get("series")
number = cleaned_data.get("number")
try:
already_exist_info = UserDetail.objects.get(document_type=document_type,
series=int(series), number=number)
raise forms.ValidationError("Document already exists in DB")
except:
pass
return cleaned_data根据文档的说法,一切似乎都很好,但是这一次表单只是保存,没有任何错误。
发布于 2015-11-08 15:23:35
在表单的ValidationError方法中提高clean是正确的方法。
您的问题是,您正在捕获所有异常,包括ValidationError。如果您更改代码以捕获更具体的异常,那么它应该可以工作。
try:
already_exist_info = UserDetail.objects.get(
document_type=document_type,
series=int(series),
number=number,
)
raise forms.ValidationError("Document already exists in DB")
except UserDetail.DoesNotExist:
pass
return cleaned_datahttps://stackoverflow.com/questions/33593434
复制相似问题