【问题标题】:Update post through function based view in Django在 Django 中通过基于函数的视图更新帖子
【发布时间】:2020-09-28 09:22:02
【问题描述】:

我一遍又一遍地寻找这个问题的答案,但找不到与我的问题相关的答案。

我的主页中有一个模式,我希望允许用户从中更新他们的帖子。我为此使用了包含标签和 fbv。

这是我的看法:

def update_view(request):
    post = get_object_or_404(Post, id=id)

    if 'submit_u_form' in request.POST:
        u_form = PostUpdateForm(request.POST or None, instance=post)
        if u_form.is_valid():
             u_form.save()

    return redirect('posts:index')

这是我的自定义标签:

@register.inclusion_tag('posts/update.html')
def update_tag():
    u_form = PostUpdateForm()
    return {'u_form': u_form}

Forms.py 在这里:

class PostUpdateForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['content', 'image', 'category',]

网址.py:

urlpatterns = [
    path('update/', update_view, name='update'),
]

我在 index.html 中的模态包括这种形式:

<form action="{% url 'posts:update' %}" method="post" enctype="multipart/form-data">
    <div class="modal-body">
        {% csrf_token %}
        <input type="hidden" name="post_id" value={{ post.id }}>
        {% update_tag %}
    </div>
    <div class="modal-footer">
        <button type="submit" value="submit" name="submit_u_form">Update Post</button>
    </div>
</form>

而update.html只包含{{ u_form }}

我的表单以我希望的方式显示在模式中,但是在提交时我收到此错误:

TypeError at /update/ Field 'id' expected a number but got &lt;built-in function id&gt;.

我曾尝试使用&lt;int:id&gt; 将 id 传递给 url,但这只会导致更多错误。

请有人向我解释我哪里出了问题以及如何解决问题?提前致谢。

【问题讨论】:

    标签: django forms simplemodal templatetags


    【解决方案1】:

    改变你的看法

    def update_view(request,id):#id
        post = get_object_or_404(Post, id=id)
        form = PostUpdateForm(instance=post)
        if request.method == "POST":
           form = PostUpdateForm(request.POST, instance=post)
           if form.is_valid():
               form.save()
    

    把你的网址改成

    path('update/<int:id>', update_view, name='update'),
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-23
      • 1970-01-01
      • 2014-02-16
      相关资源
      最近更新 更多