DJANGO:正确处理形式的正确方法,并将其发布到同一页面



我是Django的新手,并在其网站上完成了7个部分教程。其教程的第四部分在页面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)

因此,在这种情况下,当视图首先称为我时,如果存在该对象。然后,我检查一下帖子中是否有任何属性:如果是这样,我会更新模型。然后,如果模型已更新,我将httpresponsedirect到同一页面,否则我只发送渲染(第一个呼叫(

这是正确的吗?

您可以做这样的事情,

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)

最新更新