简体   繁体   English

Django表单有两个提交按钮。 。 。 一个需要字段,一个不需要

[英]Django form with two submit buttons . . . one requires fields and one doesn't

I think this should be a fairly straightforward question . 我认为这应该是一个相当简单的问题。 . . I have ONE Django form with TWO different submit buttons. 我有一个带有两个不同提交按钮的Django表单。 The first submit button is just for SAVING to the database whatever values are typed in to the form fields (so the user can come back and finish the form later if they want). 第一个提交按钮仅用于向数据库保存在表单字段中输入的任何值(因此,如果用户需要,用户可以返回并稍后完成表单)。 I want the form fields to NOT be required when this first submit button is clicked. 我希望在单击第一个提交按钮时不需要表单字段。 When the user clicks the second submit button, though, all fields should be required. 但是,当用户单击第二个提交按钮时,应该需要所有字段。 Is there a way to do this? 有没有办法做到这一点? Or do I just have to duplicate the form once for each submit button? 或者我只需要为每个提交按钮复制一次表单?

The answer above works, but I liked this way better: Changing required field in form based on condition in views (Django) 上面的答案有效,但我更喜欢这种方式: 根据视图中的条件更改表单中的必填字段(Django)

I have two buttons: 我有两个按钮:

<!-- 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">

I make all form fields required=False by default and then have this in my view: 我将所有表单字段设为required=False默认required=False ,然后在我的视图中显示:

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

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

Thanks everyone!! 感谢大家!!

If you're manually writing the HTML for the submit buttons, you can add a name and value attribute which your Django app can use: 如果您手动为提交按钮编写HTML,则可以添加Django应用程序可以使用的namevalue属性:

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

When the form is submitted, you'll be able to know which action the user intended to perform. 提交表单后,您将能够知道用户要执行的操作。

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

This shouldn't be technically possible using the 'required' field attribute because Django fields are set to optional/required on the initialization of your form. 这在技术上不可能使用'required'字段属性,因为Django字段在表单初始化时设置为optional / required。

Let's look at the django call stack: 我们来看看django调用堆栈:

  1. Views.py receives a GET-request and initializes the form using your Forms.py form class. Views.py收到GET请求并使用您的Forms.py表单类初始化表单。
  2. At this point , all your fields are created with their 'required' attributes. 此时 ,所有字段都是使用“必需”属性创建的。
  3. When you click a button, Views.py gets a POST-request. 单击按钮时, Views.py会收到POST请求。 It's too late to change the 'required' attribute of the fields because they were already set when the GET-request initialized your form 更改字段的“required”属性为时已晚,因为在GET请求初始化表单时已经设置了这些属性
  4. (The POST-request returns a redirect or a new form) (POST请求返回重定向或新表单)

If you did try changing the 'required' attribute in your POST-request and the field was empty, your form would be invalid (AKA when you call form.is_valid() it would return False). 如果您确实尝试更改POST请求中的“required”属性并且该字段为空,则表单将无效 (当您调用form.is_valid()时它将返回False)。

Caveat: Then only possible workaround would be to check for the field in your POST-request and use a Django message but that's not recommended because it disrupts the Django architecture, forcing you to reload your form (instead of redirecting) and losing the user submitted data. 警告:那么只有可能的解决方法是检查POST请求中的字段并使用Django消息,但不建议这样做,因为它会破坏Django架构,迫使您重新加载表单(而不是重定向)并丢失提交的用户数据。

UPDATE: 更新:

It's possible to do this in jquery by using a hidden submit button and a regular visible button. 通过使用隐藏的提交按钮和常规可见按钮,可以在jquery中执行此操作。 The regular button onClick calls jquery that sets whichever fields you want to required, then triggers the hidden submit button. 常规按钮onClick调用jquery,设置您想要的任何字段,然后触发隐藏的提交按钮。

 <head> <meta charset="utf-8" /> <script data-require="jquery" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script> <script> const allFields = [''] //put all your field ids here $("#tableAdd").click(function () { // Set all your fields back to optional allFields.forEach(function(field) { $( "#" + field ).removeAttr('required'); }); // Set specific fields as required, 'manufacturer_date' being the field 'table_add' requires var requiredFields = ['manufacturer_date']; requiredFields.forEach(function(field) { $( "#" + field ).attr('required', ''); }); // Then trigger the hidden input field to submit the form and send the POST request $( "#table_add" ).trigger( "click" ); }); </script> </head> <body> <input id="manufacturer_date" type="date"> <input type="button" id="tableAdd" value="Add"> <input type="submit" name="table_add" id="table_add" hidden> </body> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM