如何仅在表单验证通过后加载 Bootstrap 模式?

问题描述 投票:0回答:2

我试图弹出一个包含条款和条件的模式窗口,只有当用户接受条款和条件时,数据才会提交到数据库。我想在弹出模式之前验证用户输入。下面是我的代码。

individual_account.html

        <form method="post" class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4" id="individualForm">
            {% csrf_token %} {% for hidden_field in form.hidden_fields %} {{ hidden_field.errors }} {{ hidden_field }} {% endfor %}
            <div class="flex flex-wrap -mx-3 mb-6">
                <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0">
                    <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="{{form.full_name.id_for_label}}">
                        {{ form.full_name.label }}
                    </label>
                    {{ form.full_name }}
                    {% if form.full_name.errors %}
                        {% for error in form.full_name.errors %}
                            <p class="text-red-600 text-sm italic pb-2">{{ error }}</p>
                        {% endfor %}
                    {% endif %}
                </div>
                <div class="w-full md:w-1/2 px-3">
                    <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="{{form.id_passport_no.id_for_label}}">
                        {{ form.id_passport_no.label}}
                    </label>
                    {{ form.id_passport_no }}
                    {% if form.id_passport_no.errors %}
                        {% for error in form.id_passport_no.errors %}
                            <p class="text-red-600 text-sm italic pb-2">{{ error }}</p>
                        {% endfor %}
                    {% endif %}
                </div>
            </div>
           <!-- Button trigger modal -->
            <button type="button" class="bg-yellow-700 text-white rounded-none hover:bg-white hover:text-blue-900 hover:border-blue-900 shadow hover:shadow-lg py-2 px-4 border border-gray-900 hover:border-transparent" data-bs-toggle="modal" data-bs-target="#exampleModal">
              Create Account
            </button>

            <!-- Modal -->
            <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
              <div class="modal-dialog">
                <div class="modal-content">
                  <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Terms & Conditions</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                  </div>
                  <div class="modal-body">
                    <p>Terms & CConditions Here!!                    </p>
                    <label><input type="checkbox" id="acceptTerms"> I accept the terms and conditions</label>
                  </div>
                  <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Save changes</button>
                  </div>
                </div>
              </div>
            </div>
         </form>

views.py

def individual_account(request):
    if request.method == 'POST':
        form = IndividualForm(request.POST)
        if form.is_valid():
            form.save()
            fullname = form.cleaned_data['full_name']
            messages.success(
                request,
                f'Thank You {fullname} For Creating An Account.'
            )
            return HttpResponseRedirect(
                reverse_lazy('accounts:individual-account')
            )
    else:
        form = IndividualForm()
    return render(request, 'accounts/individual_account.html', {'form': form})

我怎样才能实现这个目标?

python-3.x django twitter-bootstrap django-views
2个回答
0
投票

因此,如果我理解正确,您只想在用户接受弹出模式时执行发布请求,您可以在模式中使用此按钮使用 javascript 发送发布请求:

<button type="button" class="btn btn-primary">Save changes</button>
由于这是一个发布请求,您需要包含您的 csrf_token。解决方法如下:

let csrfToken = "{{csrf_token}}"
async function postRequest() {
  let form = document.getElementById("individualForm")
  let postUrl = form.action;
  let data = new FormData(form)

  // include your csrf token for post request in the request header
  let headers = new Headers({
    "X-CSRFToken": csrfToken,
  });
  let postResponse = await fetch(postUrl, {
    method: "POST",
    headers: headers,
    body: data,
    redirect: "follow",
  });
}

当然,您需要一个带有您提到的按钮的 onclick 事件:

<button type="button" class="btn btn-primary" onclick="postRequest()">Save changes</button>
我还没有测试代码,但这是关于如何实现目标的一般指南,以便在发送请求之前弹出中间窗口。

注意: 您不需要使用 fetch api 来执行 post 请求,您可以通过多种方式在 javascript 中执行此操作,我最熟悉 fetch,所以请持保留态度,我希望它有所帮助。


0
投票

我设法解决了这个问题。

<form method="post" class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4" id="individualForm">
    {% csrf_token %} 
    {% for hidden_field in form.hidden_fields %}
        {{ hidden_field.errors }} 
        {{ hidden_field }} 
    {% endfor %}
    <!-- Your form fields here -->

    <!-- Button to trigger modal -->
    <button type="submit" id="createAccountBtn" class="bg-yellow-700 text-white rounded-none hover:bg-white hover:text-blue-900 hover:border-blue-900 shadow hover:shadow-lg py-2 px-4 border border-gray-900 hover:border-transparent">
        Create Account
    </button>
</form>

<!-- Modal -->
<div class="modal fade" id="termsModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Terms & Conditions</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>Terms & Conditions Here!!</p>
                <label><input type="checkbox" id="acceptTerms"> I accept the terms and conditions</label>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" id="acceptTermsBtn" class="btn btn-primary">Accept and Create Account</button>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function () {
        // Handle form submission
        $('#individualForm').submit(function (event) {
            event.preventDefault(); // Prevent default form submission
            $('#termsModal').modal('show'); // Show terms modal
        });

        // Handle accept terms button click
        $('#acceptTermsBtn').click(function () {
            if ($('#acceptTerms').prop('checked')) {
                $('#individualForm').unbind('submit').submit(); // If terms accepted, submit form
            } else {
                // If terms not accepted, show an alert or perform any other action
                alert('Please accept the terms and conditions.');
            }
        });
    });
</script>

© www.soinside.com 2019 - 2024. All rights reserved.