django form不传递表单。IS_VALID()条件
在我的视图中。 当我检查时,如果form.is_valid():
它总是返回为false,我看不到表单的问题。
views.py
def your_profile(request):
if request.method == "POST":
form = CreatePost(request.POST)
if form.is_valid():
title = form.cleaned_data.get("title_input")
media = form.cleaned_data.get("media_input")
caption = form.cleaned_data.get("caption_input")
context = {"title": "Your Profile"}
return render(request, "myApp/your_profile.html", context)
forms.py
class CreatePost(forms.Form):
title = forms.CharField(max_length=30)
media = forms.FileField(max_length=350)
caption =forms.CharField(max_length=300)
html
<form action="" method="post">
<input type="text" name="title_input" id="title_input">
<label for="title_input">Title</label>
<input type="file" name="media_input" id="media_input">
<label for="media_input">Media</label>
<input type="text" name="caption_input" id="caption_input">
<label for="caption_input">Caption</label>
<input type="submit" value="POST!">
</form>
In my views.py my have a view where a user can create a post with a title, media file and caption.
When i check if form.is_valid():
it always returns as false and i cannot see the issue with my form.
views.py
def your_profile(request):
if request.method == "POST":
form = CreatePost(request.POST)
if form.is_valid():
title = form.cleaned_data.get("title_input")
media = form.cleaned_data.get("media_input")
caption = form.cleaned_data.get("caption_input")
context = {"title": "Your Profile"}
return render(request, "myApp/your_profile.html", context)
forms.py
class CreatePost(forms.Form):
title = forms.CharField(max_length=30)
media = forms.FileField(max_length=350)
caption =forms.CharField(max_length=300)
html
<form action="" method="post">
<input type="text" name="title_input" id="title_input">
<label for="title_input">Title</label>
<input type="file" name="media_input" id="media_input">
<label for="media_input">Media</label>
<input type="text" name="caption_input" id="caption_input">
<label for="caption_input">Caption</label>
<input type="submit" value="POST!">
</form>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需在此处进行广告,就像这里一样:
它将输出
&lt; li&lt;/li&gt;
带有字段名称和错误的标签。您还忘了添加:
在.html中的
&lt; form&gt;/form&gt;/form&gt;
tag的内部另外,
name
&lt; input&gt;
标签的属性必须与模型中字段的名称相似。这总是对我有用。
Just ad the else block, like here:
It will output the
<li></li>
tag with the name of the field and the error.You also forgot to add:
Inside of your
<form></form>
tag in the .htmlAlso the
name
attributes of<input>
tags must be similar with the names of the fields in the model.This always works for me.
从HTML中的“名称”标签中删除“ _input”。表单无法找到字段值。名称标签应具有与表单类的相应属性相同的值。
Remove the "_input" from the "name" tag in HTML. The form is not able to find the field values. The name tag should have the same value as the corresponding attribute of the Form class.