我如何预先填充此更新表格

我如何预先填充此更新表格

本文介绍了我如何预先填充此更新表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在编辑表单时将表单中的数据预先填充

i want the form to be prepopulated with data when i am editing the form

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)
{% extends "List/Home.html" %}
{% block content %}

<form action="" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit">

</form>

{% endblock content %}

推荐答案

请仔细考虑如何实例化表单.目前,您正在对GET和POST请求使用相同的代码 TaskForm(request.POST,instance = post):

Think carefully about how you instantiate forms. At the moment, you are using the same code TaskForm(request.POST, instance=post) for GET and POST requests:

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请求加载表单时,会得到一个带有错误的空表单.

But request.POST is empty for GET requests, so you'll get an empty form with errors when you load the form with a GET request.

您可以通过删除GET请求的 request.POST 来解决此问题

You can fix it by removing request.POST for GET requests

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 而不是替换形式可能更清楚:

It might be clearer to use if...else instead of replacing the form:

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)


这篇关于我如何预先填充此更新表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 07:34