当我尝试发布创建新文章表单时,会遇到这样的错误:
django.utils.datastructures.MultiValueDictKeyError: "'title'"
Exception Type: MultiValueDictKeyError
Exception Value:
"'title'"
views.py,处理POST数据并将其存储到数据库,
def create_article(request, block_id):
block = Block.objects.get(id=block_id)
if request.method == "GET":
context = {'b':block}
return render(request, "article/create_article.html", context)
elif request.method == "POST":
title = request.POST['title']
content = request.POST['content']
article = Article(block=block, title=title, content=content, status=0)
article.save() # save to database
return redirect(f"article/list/{ block_id }")
models.py
class Article(models.Model):
STATUS = (
(0, 'normal'),
(-1, 'deleted'),
)
block = models.ForeignKey(Block, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
content = models.CharField(max_length=1000) # set the widget
status = models.IntegerField(choices=STATUS)
date_created = models.DateTimeField(default=datetime.now)
date_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
表单模板,使用bootstrap的样式。
<form class="form-horizontal" action="/article/create/{{ b.id }}" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="title" class="col-sm-1 control-label">Title</label>
<div class="col-sm-11">
<input type="text" class="form-control" id="title" placeholder="Write Title Later" >
</div>
</div>
<div class="form-group">
<label for="content" class="col-sm-1 control-label" >Content</label>
<div class="col-sm-11">
<textarea class="form-control" id="content" rows="10">Write Content Firslty.</textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-11">
<button type="submit" class="btn btn-primary">Publish</button>
</div>
</div>
</form>
我将标识属性添加到标记
后报告相同的错误 <div class="col-sm-11">
<input type="text" class="form-control" id="title" name="title" placeholder="Write Title Later" >
</div>
如何解决这样的问题?
答案 0 :(得分:1)
您遗漏了name
的{{1}}个参数。 input
仅由CSS和JS使用。尝试使用
id
而不是
<input type="text" class="form-control" name="title" id="title" placeholder="Write Title Later" >
答案 1 :(得分:0)
尝试提供一些默认值,如下所示
def create_article(request, block_id):
# your code
# ...
elif request.method == "POST":
title = request.POST.get('title', 'default_title') # change 1
content = request.POST.get('content', 'default_title') # change 2
article = Article(block=block, title=title, content=content, status=0)
article.save() # save to database
return redirect(f"article/list/{ block_id }")