我正在使用 Django。我创建了如下表格
表格.py
class PostForm(forms.Form):
title = forms.CharField(max_length=50, required=True)
body = forms.CharField(max_length=10000, required=True,widget=forms.Textarea(attrs={"rows":"5"}))
from_location = forms.CharField(max_length=50, required=True)
to_location = forms.CharField(max_length=50, required=True)
views.py
def create_post(request):
if request.user.is_authenticated:
post_form = PostForm(request.POST)
print('printing title..')
if request.method == 'POST':
if post_form.is_valid():
post = Post.objects.create(title = request.POST['title'], body=request.POST['body'], from_location=request.POST['from_location'], to_location=request.POST['to_location'], author = request.user, uuid = uuid.uuid4())
message = messages.success(request, f'Your post has been created!')
return redirect(reverse_lazy('posts:post'))
else:
post_form = PostForm()
return redirect(reverse_lazy('posts:post'))
context = {
'post_form':post_form
}
return render(request, 'posts/create_post.html', context)
我在所有表单字段上都出现了红色边框。我意识到 crispy-forms 已经将
is-invalid
类添加到所有字段中。如果我在表单中设置 required=False,错误就消失了。
电流输出
预期输出是没有红色边框和警告的上图
我尝试从开发工具中删除该类并且它起作用了。我问了 chatGPT 并尝试了它的方法,但没有帮助
你遇到这个问题是因为在你的 views.py 文件中
post_form = PostForm(request.POST)
在 if request.method == 'POST'
POST 请求检查之外。
将您的 views.py 文件更新为:
def create_post(request):
if request.user.is_authenticated:
if request.method == 'POST':
post_form = PostForm(request.POST)
if post_form.is_valid():
post = Post.objects.create(title=request.POST['title'], body=request.POST['body'], from_location=request.POST['from_location'], to_location=request.POST['to_location'], author=request.user, uuid=uuid.uuid4())
messages.success(request, f'Your post has been created!')
return redirect(reverse_lazy('posts:post'))
else:
post_form = PostForm()
else:
return redirect(reverse_lazy('posts:post'))
context = {
'post_form': post_form
}
return render(request, 'posts/create_post.html', context)
这将解决页面上渲染时的表单有效性问题。在页面上呈现表单或传递
request.POST
表单数据之前,您应该始终先检查表单方法请求。