为什么我的Django表格执行了两次?

时间:2022-10-13 20:32:01

Can someone explain to me why form 2 executed twice? In another word, I would see 2 print statements, "Hello from form 2," in the console.

有人可以向我解释为什么表格2执行两次?换句话说,我会在控制台中看到2个打印语句,“表单2中的Hello”。

The first print statement occurred after I clicked "Submit" from form 1. Second print statement comes after the second "Submit" I clicked from form 2. How do I make it to only print once?

第一个打印声明是在我从表单1中单击“提交”后发生的。第二个打印声明出现在第二个“提交”之后,我从表单2中单击。如何使其仅打印一次?

views.py

def form1 (request):

    NameFormSet = formset_factory (NameForm, formset = BaseNodeFormSet, extra = 2, max_num = 5)

    if request.method == 'POST':

        name_formset = NameFormSet (request.POST, prefix = 'nameform')

        if name_formset.is_valid ():
            data = name_formset.cleaned_data
            request.session ['data'] = data

            return HttpResponseRedirect ('form2')
        else:
            name_formset = NameFormSet (prefix = 'nameform')

     context = {'name_formset': name_formset}

     return render (request, 'nameform/form1.html', context)


def form2 (request):

    data = request.session ['data']
    print ('Hello from form 2')    # <====  This statement printed twice in the console

    CheckBoxFormSet = formset_factory (CheckBox, extra = 2, max_num = 5)

    if request.method == 'POST':

        checkbox_formset = CheckBoxFormSet (request.POST, prefix = 'checkbox')

        if checkbox_formset.is_valid ():
            for i, form in enumerate (checkbox_formset.cleaned_data):
                data [i].update (form)      # Join cleaned data with original data

            del request.session ['data']
            context = {'data': data}
            return render (request, 'nameform/success.html', context)

            checkbox_formset = CheckBoxFormSet (prefix = 'checkbox')

     context = {'checkbox_formset': checkbox_formset, 'data': data}
     return render (request, 'nameform/form2', context)

Update 1: The "print" statement is actually a backend method that processes the data obtained from form 1 and display it in form 2. Leaving where it is now would cause that method to process the information twice. I have no issue or error doing it this way but it's unnecessary.

更新1:“print”语句实际上是一个后端方法,它处理从表单1获得的数据并以表单2显示它。离开现在的位置将导致该方法处理信息两次。我这样做没有问题或错误,但这是不必要的。

For example:

def form2 (request):

    data = request.session ['data']
    n, errors = getInfo (data)    # <====  This statement performed twice in the console
    if request.method = 'POST':
    ....    
        if checkbox_formset.is_valid ():
            for i, form in enumerate (checkbox_formset.cleaned_data):
                data [i].update (form)      # Join cleaned data with original data

            n.process_new_data (data, errors)
            del request.session ['data']

            context = {'data': data, 'errors': error}
            return render (request, 'nameform/success.html', context)

    else:
        checkbox_formset = CheckBoxFormset (prefix = 'checkbox')

    context = {'data': data, 'errors': error}
    return render (request, 'nameform/form2.html', context)

Update 2: Since my explanation is a little long, allow me address Ale question here.

更新2:由于我的解释有点长,请允许我在这里解决问题。

Yes, I fully understand why it processed twice. To briefly answer your question, putting getInfo inside 'POST' will give me a context, unbound error because of the context "errors" dictionary doesn't exist in the first redirect.

是的,我完全理解为什么它处理了两次。要简要回答你的问题,将getInfo放在'POST'中会给我一个上下文,因为上下文中的错误“错误”字典在第一次重定向中不存在。

context = {'data': data, 'errors': errors}

I'd to update my post so that I can explain why I can't use your method. GetInfo takes the data from form1, processes it, and passes it on to form 2 to display. I could do all that in form1 but then I would have to redo it in form2 because form2 will not know what 'n' or 'errors' is without passing it through sessions. I'm just trying to see if there's a better way to do this.

我要更新我的帖子,以便我可以解释为什么我不能使用你的方法。 GetInfo从form1获取数据,处理它,并将其传递给表单2进行显示。我可以在form1中完成所有这些,但后来我必须在form2中重做它,因为form2不知道'n'或'errors'是什么而不通过会话传递它。我只是想看看是否有更好的方法来做到这一点。

2 个解决方案

#1


The form2 view is run twice, once as a redirect from form1 which creates the form and renders the template, missing the if request.method == 'POST' part as this time around the request is a 'GET'.

form2视图运行两次,一次作为来自form1的重定向,创建表单并呈现模板,缺少if request.method =='POST'部分,因为此时请求周围是'GET'。

When you submit form2 back to the same view method it prints the line you indicate again, this time the code in the if block executes as the request is a 'POST'.

当您将form2提交回相同的视图方法时,它会再次打印您指定的行,这次if块中的代码将执行,因为请求是“POST”。

The key is this line that redirects to the form2 view:

关键是这一行重定向到form2视图:

return HttpResponseRedirect ('form2')

#2


You can debug this by including the stacktrace to you print statements:

您可以通过将stacktrace包含在print语句中来调试它:

import traceback
print ''.join(traceback.format_stack())

#1


The form2 view is run twice, once as a redirect from form1 which creates the form and renders the template, missing the if request.method == 'POST' part as this time around the request is a 'GET'.

form2视图运行两次,一次作为来自form1的重定向,创建表单并呈现模板,缺少if request.method =='POST'部分,因为此时请求周围是'GET'。

When you submit form2 back to the same view method it prints the line you indicate again, this time the code in the if block executes as the request is a 'POST'.

当您将form2提交回相同的视图方法时,它会再次打印您指定的行,这次if块中的代码将执行,因为请求是“POST”。

The key is this line that redirects to the form2 view:

关键是这一行重定向到form2视图:

return HttpResponseRedirect ('form2')

#2


You can debug this by including the stacktrace to you print statements:

您可以通过将stacktrace包含在print语句中来调试它:

import traceback
print ''.join(traceback.format_stack())