Django编辑帖子视图未使用现有数据填充表单字段。

huangapple go评论46阅读模式
英文:

Django edit_post view not prepopulating form fields with existing data

问题

我正在开发一个Django博客应用程序,我有一个用于编辑帖子的视图。但是,当我点击编辑按钮时,表单字段不会显示预填充的现有数据。

这是我的`edit_post`视图代码:

```python
def edit_post(request, post_id):
    post = get_object_or_404(Post, id=post_id)

    if request.method == "POST":
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            form.save()
            return redirect("main_page")
    else:
        form = PostForm(instance=post)

    context_dict = {
        "form": form,
        "post": post,
    }

    return render(request, "blog/edit_post.html", context_dict)

all_posts.html -> 按钮,重定向到编辑帖子页面。

{% csrf_token %}

edit_post.html: 表单部分的代码。

{% csrf_token %}
{{ form.media }}


{{ form.title }}

{{ form.summary }}

{{ form.image_url }}

{{ form.body }}

{{ form.tags }}


我已经确认PostForm正确配置了来自Post模型的必填字段。我还尝试过使用@never_cache装饰器,但没有解决这个问题。

我不确定为什么在提交表单后表单字段没有预填充现有数据。只有在我手动重新加载页面时才起作用。

对于如何解决这个问题的任何建议或见解,将不胜感激。


<details>
<summary>英文:</summary>

I&#39;m developing a Django blog application and I have a view to edit a post. However, when I click the Edit button, the form fields do not appear prepopulated with the existing data.

Here&#39;s my `edit_post` view code:


def edit_post(request, post_id):
post = get_object_or_404(Post, id=post_id)

if request.method == &quot;POST&quot;:
    form = PostForm(request.POST, instance=post)
    if form.is_valid():
        form.save()
        return redirect(&quot;main_page&quot;)
else:
    form = PostForm(instance=post)

context_dict = {
    &quot;form&quot;: form,
    &quot;post&quot;: post,
}

return render(request, &quot;blog/edit_post.html&quot;, context_dict)

all_posts.html -&gt; button that redirects to the Edit Post page.

    &lt;form method=&quot;POST&quot; action=&quot;{% url &#39;edit_post&#39; post.id %}&quot;&gt;
        {% csrf_token %}
        &lt;button type=&quot;submit&quot; class=&quot;btn btn-secondary me-2 btn-sm&quot;&gt;Edit&lt;/button&gt;
    &lt;/form&gt;

edit_post.html: part of the code where the form is.

    &lt;form method=&quot;POST&quot;&gt;
                    {% csrf_token %}
                    {{ form.media }}
                    &lt;div class=&quot;mb-3&quot;&gt;
                        &lt;label for=&quot;{{ form.title.id_for_label }}&quot; class=&quot;form-label&quot;&gt;Title&lt;/label&gt;
                        {{ form.title }}
                    &lt;/div&gt;
                    &lt;div class=&quot;mb-3&quot;&gt;
                        &lt;label for=&quot;{{ form.summary.id_for_label }}&quot; class=&quot;form-label&quot;&gt;Summary&lt;/label&gt;
                        {{ form.summary }}
                    &lt;/div&gt;
                    &lt;div class=&quot;mb-3&quot;&gt;
                        &lt;label for=&quot;{{ form.image_url.id_for_label }}&quot; class=&quot;form-label&quot;&gt;Image URL&lt;/label&gt;
                        {{ form.image_url }}
                    &lt;/div&gt;
                    &lt;div class=&quot;mb-3&quot;&gt;
                        &lt;label for=&quot;{{ form.body.id_for_label }}&quot; class=&quot;form-label&quot;&gt;Body&lt;/label&gt;
                        {{ form.body }}
                    &lt;/div&gt;
                    &lt;div class=&quot;mb-3&quot;&gt;
                        &lt;label for=&quot;{{ form.tags.id_for_label }}&quot; class=&quot;form-label&quot;&gt;Tags&lt;/label&gt;
                        {{ form.tags }}
                    &lt;/div&gt;
                    &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Update Post&lt;/button&gt;
                &lt;/form&gt;  

I have verified that the PostForm is correctly configured with the required fields from the Post model. I also tried using the `@never_cache` decorator, but it didn&#39;t resolve the issue.

I&#39;m not sure why the form fields are not prepopulated with the existing data after submitting the form. It only works when I manually reload the page.

Any suggestions or insights on how to fix this issue would be greatly appreciated.

</details>


# 答案1
**得分**: 1

尝试以下两种方法来解决这个问题。

检查这段代码,确保你的 post 对象不为空。

```python
post = get_object_or_404(Post, id=post_id)

其次,从上下文中移除 post 对象,它不是必需的。

context_dict = {
    "form": form,
}
英文:

Try these two things to solve the issue.

Check this code, your post object should be not null.

post = get_object_or_404(Post, id=post_id)

Second remove post object from context, it's not required.

context_dict = {
            &quot;form&quot;: form,
            }

答案2

得分: 1

好的,“the problem is the button”这部分是指问题出在按钮上,它会将用户带到“编辑帖子视图”。

“But your button strangely is also sending a POST request.”这部分是指但你的按钮却奇怪地也发送了一个POST请求。你需要更改这个。

“This can be just a normal link like this:”这部分是指这可以只是一个普通的链接,就像这样:

“Just because you are passing a parameter to the url does not mean that this has to be a POST request!”这部分是指仅仅因为你向URL传递了参数,并不意味着它必须是一个POST请求!

“What is happening in your case: Your post-edit-view divides its logic into POST and GET requests.”这部分是指在你的情况下发生了什么:你的“编辑帖子视图”将其逻辑分为了POST和GET请求。

“Usually you expect the GET part of the view being triggered when a user "goes" to the edit-view.”这部分是指通常你期望在用户“进入”编辑视图时会触发视图的GET部分。

“Then the form would be populated correctly via PostForm(instance=post).”这部分是指然后表单将通过PostForm(instance=post)正确填充。

“In your case you access the view already with a POST request, so the POST arm of the view gets triggered.”这部分是指在你的情况下,你已经使用了一个POST请求访问了视图,所以视图的POST部分被触发了。

“Here you don't send any data with the request, so this PostForm(request.POST, instance=post) populates the form with empty data.”这部分是指在这里,你没有在请求中发送任何数据,所以PostForm(request.POST, instance=post)会用空数据填充表单。

英文:

Ok, the problem is the button which brings the user to the post-edit-view!

You only want to issue a POST request when you want to send data with the request. But your button strangely is also sending a POST request. You have to change that. This can be just a normal link like this:

&lt;a href=&quot;{% url &#39;edit_post&#39; post.id %}&quot; class=&quot;btn btn-secondary me-2 btn-sm&quot;&gt;
  Edit
&lt;/a&gt;

Just because you are passing a parameter to the url does not mean that this has to be a POST request!

What is happening in your case: Your post-edit-view divides its logic into POST and GET requests. Usually you expect the GET part of the view being triggered when a user "goes" to the edit-view. Then the form would be populated correctly via PostForm(instance=post). In your case you access the view already with a POST request, so the POST arm of the view gets triggered. Here you don't send any data with the request, so this PostForm(request.POST, instance=post) populates the form with empty data.

huangapple
  • 本文由 发表于 2023年6月27日 19:38:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76564467.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定