当用户提交表单并引发ValidationError异常时,我正在尝试验证表单字段是否为None:
def clean_street_number(self):
if self.cleaned_data['street_number'] is None:
raise ValidationError(
('You forgot to write your street number')
)
else:
return self.cleaned_data['street_number']
当我填写表格并提交没有街道号码时,Django会崩溃并显示消息:
The view core.decorators.add_location didn't return an HttpResponse object. It returned None instead.
views.py
def add_property_location(request):
if request.method == 'POST':
form = LocationForm(request.POST)
if form.is_valid():
p = form.save(commit=False)
p.user = get_object_or_404(User, pk=request.user.pk)
p.save()
return redirect('add_description')
else:
form = LocationForm()
return render(request, 'add_location.html', {'form': form})
答案 0 :(得分:1)
正如错误所示,当表单无效时,您的视图不会返回对帖子请求的响应。
您可以通过将最终return语句移出if块来解决此问题。这样,视图将呈现模板并显示无效的表单及其错误。
else:
form = LocationForm()
return render(request, 'add_location.html', {'form': form})