我希望在编辑表单时将表单中的数据预先填充
views.py
def edit_task(request, post_id):
post = Post.objects.get(id=post_id)
form = TaskForm(request.POST, instance=post)
if request.method == 'POST':
print(request.POST)
form = TaskForm(request.POST, instance=post)
if form.is_valid():
form.save()
return redirect('task')
context = {'form': form}
return render(request, 'List/add_task.html', context)
add_task.html
{% extends "List/Home.html" %}
{% block content %}
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit">
</form>
{% endblock content %}
答案 0 :(得分:1)
您可以使用数据填充此表单,并提供return "${df.format(length / 1024.f)} KB";
initial
答案 1 :(得分:1)
请仔细考虑如何实例化表单。目前,您正在对GET和POST请求使用相同的代码TaskForm(request.POST, instance=post)
:
def edit_task(request, post_id):
post = Post.objects.get(id=post_id)
form = TaskForm(request.POST, instance=post)
if request.method == 'POST':
print(request.POST)
form = TaskForm(request.POST, instance=post)
...
但是request.POST
对于GET请求为空,因此,当使用GET请求加载表单时,您会得到一个带有错误的空表单。
您可以通过删除GET请求的request.POST
来解决此问题
def edit_task(request, post_id):
post = Post.objects.get(id=post_id)
# Instantiate form without any data
form = TaskForm(instance=post)
if request.method == 'POST':
print(request.POST)
# replace the form for POST requests
form = TaskForm(request.POST, instance=post)
...
使用if...else
而不是替换表单可能更清楚:
def edit_task(request, post_id):
post = Post.objects.get(id=post_id)
if request.method == 'POST':
print(request.POST)
# instantiate form for POST requests
form = TaskForm(request.POST, instance=post)
...
else:
# instantiate the form for GET requests
form = TaskForm(instance=post)
context = {'form': form}
return render(request, 'List/add_task.html', context)