Django:使用POST处理表单到同一页面的正确方法

时间:2017-06-04 16:10:38

标签: python django python-3.x

我是Django的新手,并在他们的网站上完成了7部分教程。他们的教程Part four在页面details上引入了一个表单,该表单发布到votes(一个不显示任何内容的视图),然后在成功时返回results或以其他方式返回给您到details

但是,如果你有一个你想要自己发布的页面怎么办(例如更新与该页面相关的东西的值,这是计算服务器端的。)

注意:我已经让这个工作了,但我想知道我是否做得对,因为我对一些事情感到困惑。

所以我的页面的代码目前看起来像:

def post_to_self_page(request, object_id):

    obj = get_object_or_404(Obj, pk=object_id)

    # if update sent, change the model and save it
    model_updated = False
    if 'attribute_of_obj' in request.POST.keys():
        obj.attribute_of_obj = request.POST['attribute_of_obj']
        obj.save()
        model_updated = True

    # do some stuff with obj

    # specify the context
    context = {
    'obj': obj,
    }
    if model_updated:
        # good web practice when posting to use redirect
        return HttpResponseRedirect(reverse('my_app:post_to_self_page', args=(object_id,)))
    return render(request, 'my_app/post_to_self_page.html', context)

所以在这种情况下,当第一次调用视图时,我会抓取该对象(如果存在)。然后我检查POST中是否有任何属性:如果是,我更新模型。然后,如果模型被更新,我使用HttpResponseRedirect到同一页面,否则我只发送使用渲染(第一次调用)

这是对的吗?

1 个答案:

答案 0 :(得分:1)

你可以这样做,

def post_to_self_page(request, object_id):
    obj = get_object_or_404(Obj, pk=object_id)
    if request.method == 'POST':
        obj.attribute_of_obj = request.POST['attribute_of_obj'] 
        obj.save() 
    context = { 'obj': obj, }
    return render(request, 'my_app/post_to_self_page.html', context)