2016-02-27 58 views
4

我认为这应该是一个相当直接的问题。 。 。我有两个不同的提交按钮的Django窗体。第一个提交按钮仅仅用于保存数据库,无论输入什么值到表单域(所以用户可以返回并在以后完成表单)。我想要单击第一个提交按钮时不需要表单域。但是,当用户点击第二个提交按钮时,所有字段都应该是必需的。有没有办法做到这一点?或者我只需要为每个提交按钮复制一次表单?Django窗体有两个提交按钮。 。 。一个需要字段,一个不需要

回答

4

上述工程的答案,但我更喜欢的是这样的:Changing required field in form based on condition in views (Django)

我有两个按钮:

<!-- simply saves the values - all fields aren't required unless the user is posting the venue --> 
<input type="submit" name="mainForm" value="Save"> 

<!-- post the values and save them to the database - fields ARE required--> 
<input type="submit" name="postVenue" value="Post Venue"> 

我让所有的表单域required=False默认,然后有这样的我查看:

if 'postVenue' in request.POST: 
    form = NewVenueForm(request.POST) 
    required = 'postVenue' in request.POST 
    form.fields['title'].required = required 
    form.fields['category'].required = required 
    # do this for every form field 

elif 'mainForm' in request.POST:  
    form = NewVenueForm(request.POST) 

谢谢大家!

3

如果你手工编写的提交按钮的HTML,你可以添加一个namevalue属性您的Django应用程序可以使用的:

<button name="action" value="save">Save</button> 
<button name="action" value="submit">Submit</button> 

当提交表单时,你就可以知道用户想要执行的动作。

class MyForm(forms.Form): 

    def __init__(self, data=None, *args, **kwargs): 
     super(MyForm, self).__init__(data=data, *args, **kwargs) 

     # store user's intended action in self.action 
     self.action = data.get('action') if data else None 

     # set form fields to be not required if user is trying to "save" 
     if self.action == 'save': 
      for field in self.fields: 
       field.required = False 
+0

谢谢!但是我对表单的__init__函数不是很熟悉,当我使用这段代码的时候,我得到一个错误,说“name'data'没有被定义”在行上“self.action = data.get('action')if data否则无“? – laurenll

+0

您需要在'__init__'方法签名中添加'data = None' –

+0

@laurenll这个答案有帮助吗?让我知道如果您有任何问题或澄清,我会很乐意更新答案 –