为什么我的Django表单执行两次? [英] Why is My Django Form Executed Twice?

查看:231
本文介绍了为什么我的Django表单执行两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



第一个打印语句发生在我从表单中单击提交 2.第二个打印声明是从表单2中点击的第二个提交之后。如何使其仅打印一次?



views.py

  def form1(request):

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

如果request.method =='POST':

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

如果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('Form from Form 2')#< ====这个语句在控制台中打印两次

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

如果request.method =='POST':

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

如果checkbox_formset.is_valid():
for i,form in enumerate(checkbox_formset.cleaned_data):
data [i] .update(form)#加入原始数据的清理数据

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

checkbox_formset = CheckBoxFormSet(prefix ='checkbox')

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

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



例如:

  def form2(request):

data = request.session ['data']
n,errors = getInfo(data)#< ====这个语句在控制台
中执行两次,如果request.method ='POST':
....
if checkbox_formset.is_valid():
for i,form in enumerate(checkbox_formset。 clean_data):
data [i] .update(form)#使用原始数据加入清理的数据

n.process_new_data(数据,错误)
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 ren (请求,'nameform / form2.html',上下文)

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



是的,我完全明白为什么它被处理了两次。要简单地回答你的问题,将getInfo放在'POST'中会给我一个上下文,因为上下文错误字典在第一个重定向中不存在,所以没有绑定错误。

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

我会更新我的帖子,以便我可以解释为什么我不能使用你的方法。 GetInfo从form1获取数据,处理它,并将其传递给表单2进行显示。我可以在form1中执行所有操作,但是我必须在form2中重做它,因为form2将不知道'n'或'errors'是不通过会话传递的。

解决方案

form2视图运行两次,一次为一个重定向从form1创建表单并渲染模板,如果request.method =='POST'部分作为这个时间周围的请求,缺少是一个GET。



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



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

  return HttpResponseRedirect('form2')


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.

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?

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.

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.

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.

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.

解决方案

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'.

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'.

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

return HttpResponseRedirect ('form2')

这篇关于为什么我的Django表单执行两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆