2017-05-04 73 views
0

嗨,我有一个HTML文件中的窗体。使用request.form使用Python和Flask处理输入数据。不过,我希望一些输入字段是可选的。目前我收到以下错误:我可以使HTML输入表单域可选吗?

400 Bad Request: The browser (or proxy) sent a request that this server could not understand. 

我相信这是由于某些字段为空。

我的形式被设计成当一个单选按钮被选中,有些字段只出现一种方法。当表单被提交并且单选按钮没有被选中时,问题就会出现,因为表单会将它们视为空。

这里是我的表单代码:

<form action = "makeBooking" method = "POST" > 
     Booking ID <input type = "number" name = "bookingid" ><br> 
     Customer ID <input type = "number" name = "customerid" ><br> 
     <input type="radio" name="choice"> 
     <label for="choice">Tick if new customer</label> 
     <div class="reveal-if-active"> 
      First Name <input type = "test" name = "firstname" VALUE="x" ><br> 
      Surname <input type = "text" name = "surname" VALUE="x"><br> 
      Billing Address <input type = "text" name = "address" VALUE="x" ><br> 
      Email <input type = "text" name = "email" VALUE="x"><br> 
     </div> 
     Flight ID <input type = "number" name = "flightid" ><br> 
     Number of Seats <input type = "number" name = "numofseats" ><br> 
     <input type = "submit" value = "Submit" > 
    </form> 

以下Python代码就是如果单选按钮没有被选中,因为他们提交的空的错误所在。

bookingid = request.form['bookingid'] 
customerid = request.form['customerid'] 
flightid = request.form['flightid'] 
numseats = request.form['numofseats'] 

if request.form['choice']: 
    firstname = request.form['firstname'] 
    surname = request.form['surname'] 
    address = request.form['address'] 
    email = request.form['email'] 

    #do some SQL insert statements with ALL the form data 

else: 
    #do some sql insert statements with the none hidden statements 

任何人有任何想法。

谢谢。

更新:为了更清楚地显示我的代码。

+0

你应该只执行在单选按钮的选择所提到的Python代码,所以给出的答案可能会做的伎俩不处理这一点。无关;你不应该使用复选框而不是单独的单选按钮吗?您无法轻易取消选中这些内容,因此用户会错误地强制他们填写表单的显示部分。 –

回答

1
if request.form['choice']: 
    firstname = request.form['firstname'] 
    surname = request.form['surname'] 
    address = request.form['address'] 
    email = request.form['email'] 

,因为你想,如果无线电选择不选择

+0

请缩进您的代码。 –

+0

现在快乐@LennartKloppenburg – Exprator

+0

感谢您的回复。不知道我很理解。我目前有你的建议(将更新我的文章,以反映),它会导致错误,因为如果单选按钮未选中,我无法处理表单数据。我希望它是'如果检查进程所有字段处理非隐藏窗体',但我不能这样做,因为如果任何字段为空,则会引发错误。 –

相关问题