具有两种形式的Django页面:如何仅发布一种形式而不刷新页面

时间:2019-04-21 07:47:17

标签: javascript html django django-forms django-views

我有一页,有两种形式。根据所选的单选按钮(默认情况下已选择一个),将显示一个表单,而另一个隐藏(使用JS和CSS)。当用户填写表单字段并提交表单时,两个表单都会通过验证,页面会刷新。我希望实现在提交表单时仅验证相应的表单,并且不刷新页面。

如何只验证一种表单并阻止刷新页面(即在提交后继续显示手动表单)?

寻找解决方案时,以下建议不能解决问题: Proper way to handle multiple forms on one page in DjangoHow to submit form without refreshing page using Django, Ajax, jQuery?http://jquery.malsup.com/form/

views.py

from flap.forms import FlapManualForm
from flap.forms import FlapAutoForm

def index(request):
    if request.method == 'POST':
        form_manual = FlapManualForm(request.POST)
        form_auto = FlapAutoForm(request.POST)
        if form_manual.is_valid():
            try:
                if form_manual.data['flap']:
                    print(form_manual.data['flap'])
                    manual = request.POST['flap']
            except:
                print('manual form empty')

        if form_auto.is_valid():
            try:
                if form_auto.data['flap_time']:
                    print(form_auto.data['flap_time'])
                    auto = request.POST['flap_time']
            except:
                print('auto form empty')

    else:
        form_manual = FlapManualForm()
        form_auto = FlapAutoForm()

    return render(request, 'index.html', {'form_manual': form_manual, 'form_auto': form_auto})

forms.py

class FlapManualForm(forms.Form):
    flap = forms.CharField(min_length=4, max_length=4, label=False, required=False, widget=forms.TextInput(attrs={'style': 'width:90px'}))
    def clean(self):
        cleaned_data = super(FlapManualForm, self).clean()
        flap = cleaned_data.get('flap')
        if not flap:
            pass

class FlapAutoForm(forms.Form):
    flap_time = forms.IntegerField(min_value=1, label=False, required=False, widget=forms.NumberInput(attrs={'style': 'width:90px'}))
    def clean(self):
        cleaned_data = super(FlapAutoForm, self).clean()
        flap_time = cleaned_data.get('flap_time')
        if not flap_time:
            pass

index.html

{% load widget_tweaks %}
<!DOCTYPE html>
<html lang="en">
<head>
  {% block title %}<title>flap</title>{% endblock %}
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
</head>
<body>

<style>
.content {
    max-width: 500px;
    margin: auto;
}
.align_center{
    text-align: center;
}
.auto_form {
    display: block;
}
.manual_form {
    display: none;
}
input[type=text] {
    margin: auto;
    text-align: center;
}
input[type=number] {
    margin: auto;
    text-align: center;
}
</style>

<script type="text/javascript">
function show_auto(){
  var x = document.getElementById("manual_form");
  var y = document.getElementById("auto_form");
  if (x.style.display === "none") {
    x.style.display = "block";
    y.style.display = "none";
  } else {
    x.style.display = "none";
    y.style.display = "block";
  }
}
function show_manual(){
  var x = document.getElementById("manual_form");
  var y = document.getElementById("auto_form");
  if (y.style.display === "none") {
    y.style.display = "block";
    x.style.display = "none";
  } else {
    y.style.display = "none";
    x.style.display = "block";
  }
}
</script>

<br>
<br>
<br>
<br>

<div class="align_center">
  <div class="btn-group" data-toggle="buttons">
    <label class="btn btn-primary active" onclick="show_auto();">
      <input type="radio" name="tab" value="igotnone" checked/>auto
    </label>
    <label class="btn btn-primary" onclick="show_manual();">
      <input type="radio" name="tab" value="igottwo"/>manual
    </label>
  </div>

  <br>
  <br>

  <div id="manual_form" class="manual_form">
    <form method="post">
      {% csrf_token %}
      {{ form_manual }}
      <button type="submit" name="manual_submit" class="btn btn-primary">flap</button>
    </form>
  </div>

  <div id="auto_form" class="auto_form">
    <form method="post">
      {% csrf_token %}
      {{ form_auto }}
      <button type="submit" name="auto_submit" class="btn btn-primary">auto</button>
    </form>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>

0 个答案:

没有答案