我想知道如何在form.save之前显示对Django forms.ValidationError/message.error
友好,而messages.error
无效并且ValidationError
像程序bug
一样丑陋不适用于客户:
views.py的部分代码如下:
class ProjectCreateView(CreateView):
model = Project
form_class = ProjectForm
def form_valid(self, form):
request = self.request
for u in user_project:
user_times = int(sum(t['learn_times'] for t in times))
if user_times >= 8 or int(request.POST.get('learn_times')) + user_times >= 8:
# messages.error didn't work
messages.error(self.request, u.username + "'s learn_times is more than 8 hours, please check!")
# ValidationError is ugly like a bug of program not for clients
raise forms.ValidationError(str(u) + "'s learn_times is more than 8 hours, please check!"
else:
pass
project = form.save(commit=False)
project.save()
form.save_m2m()
messages.success(self.request, 'Project created successfully!')
return super(CoursePermitCreateView, self).form_valid(form)
def get_success_url(self):
return reverse('project_change', kwargs={'pk': self.object.pk})
我不能在forms.py中添加forms.ValidationError,也不能在views.py中添加form.add_error,如下面的代码屏幕快照{code link),就像我添加test = Test.objects时一样.get(pk = self.kwargs ['pk'])在form.py的ProjectForm中,我将得到'ProjectForm' object has no attribute 'kwargs'
的错误!并且如果我在Forms.py的Projectform中使用request.POST.get()
,也会得到'ProjectForm' object has no attribute request
的错误。
非常感谢您提供任何建议。