如何使用Django发布表单而不重新加载页面

时间:2018-12-28 18:44:36

标签: javascript python jquery ajax django

我正在开发一个应用程序,用户将在其中提交一个值,我想在提交时隐藏包含表单的div并显示包含结果的div。目标是让他们提交表单并显示其他隐藏的div。 Django代码或Javascript我怎么了?

views.py

from django.shortcuts import render
from .models import VintageMac
from .forms import VintageMacForm

def home(request):
    if request.method == "POST":
        form = VintageMacForm(request.POST)
        if form.is_valid():
            form.save()
            form = VintageMacForm()
    else:
        form = VintageMacForm()
    return render(request, 'hmwypapp/index.html', {'form': form})

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
]

models.py

from django.conf import settings
from django.db import models
from django.utils import timezone
from django import forms

class VintageMac(models.Model):
    price = models.IntegerField()

    def publish(self):
        self.save()

    def __str__(self):
        return '%s' % (self.price)

forms.py

from django import forms

from .models import VintageMac

class VintageMacForm(forms.ModelForm):
    class Meta:
        model = VintageMac
        fields = ('price',)

HTML

<div id="submission1">
                    <p class="card-text">Some quick example text to build on the card title.</p>
                    <div class="bottom">
                      <div class="row">
                        <form action="/create_post/" class="w-100" method="POST" id="form1">
                          <div class="col-12">
                            {% csrf_token %}
                              {% for hidden_field in form.hidden_fields %}
                                {{ hidden_field }}
                              {% endfor %}
                            {% for field in form.visible_fields %}
                              <div class="form-control">
                                  {% render_field field min="0" class="form-control" id="amount1" placeholder="Type an amount." %}
                                  {% if field.help_text %}
                                <small class="form-text text-muted">{{ field.help_text }}</small>
                                {% endif %}
                              </div>
                            {% endfor %}
                          </div>
                          <div class="col-12">
                            <button onclick="myFunction1()" class="mt-1 text-center form-control btn submit-btn">Submit <span></span></button>
                          </div>
                        </form>
                      <div class="text-center credit mt-2 w-100">Submitted by @peterdenatale</div>
                      </div>
                    </div></div>
                    <div id="results1">
                      <p class="card-text">You said that you would pay <span class="value">$375.00</span> .</p>
                      <div class="bottom">
                          <div class="row">
                              <div class="col-12">
                                  <div class="progress">

                                    <div class="progress-bar" role="progressbar" aria-valuenow="65" aria-valuemin="0" aria-valuemax="100" style="width: 65%;">
                                    </div>
                                  </div>
                                  <div class="row" style="margin-bottom: -20px;">
                                    <p class="col-4 raised-text"><strong>Min<br>$0.00</strong></p>
                                    <p class="col-4 average-text"><strong>Avg<br>$250.00</strong></p>
                                    <p class="col-4 goal-text"><strong>Max<br>$500.00</strong></p>
                                  </div>
                              </div>
                            </div>
                      </div>
                    </div>

JavaScript

$(document).on('submit','#form1',function(e){
e.preventDefault();

$.ajax({
    type:'POST',
    url: '',
    data:{
        amount: $('#amount1').val(),
    },
    success:function(){
        $('#submission1').fadeOut(500);
        $('#results1').delay(500).fadeIn(500);
    }
});

我尝试将JavaScript更改为一堆不同的东西,但是它唯一的作用是重新加载页面。我想摆脱重新加载并保留在同一页面上,但仍然发布数据并隐藏/显示div。

2 个答案:

答案 0 :(得分:0)

在线:

<button onclick="myFunction1()" class="mt-1 text-center form-control btn submit-btn">Submit <span></span></button>

删除onclick处理程序,将属性type添加为值submit

更新的行应如下所示:

<button type="submit" class="mt-1 text-center form-control btn submit-btn">Submit <span></span></button>

并将url选项对象中的$.ajax键更新为/create_post/(来自form标签action属性)

答案 1 :(得分:0)

1-我想您忘了关闭javascript标签,这就是为什么它不起作用的原因。 2-更改提交按钮,使其像这样:

<input type="submit" class="mt-1 text-center form-control btn submit-btn" value="Submit"><span></span></div>

3-您也忘记了在ajax中添加csrf令牌,应该是这样的:

csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),

干杯:)