如何使用Django-ajax-json将数据保存到数据库中?

时间:2019-03-11 03:14:34

标签: json ajax django

我无法使用Django-ajax-json将数据保存到数据库中。 以下是我的代码:

这是views.py:

def new_stok(request, pk):
    supplier = get_object_or_404(Supplier, pk=pk)
    data = dict() 
    if request.method == 'POST':
        form = NewStokForm(request.POST)
        if form.is_valid():
            form.save()
            data['form_is_valid'] = True
            stoks = supplier.stoks.all()
            data['html_stok_list'] = render_to_string('stoks2.html',{'pk':supplier.pk,'stoks':stoks})
        else:
            data['form_is_valid'] = False
    else:
        form = NewStokForm()

    context = {'supplier': supplier, 'form': form}
    data['html_form'] = render_to_string('includes/partial_stok_create.html',
        context,
        request=request,
    )
    return JsonResponse(data)

javascript文件:stok.js

$(function () {
$(".js-create-book").click(function () {
      var data_id = $(this).attr("data-id");
      $.ajax({
      url: '/supplier/' + data_id + '/new/',
      type: 'get',
      dataType: 'json',
      beforeSend: function () {
        $("#modal-book").modal("show");
      },
      success: function (data) {
        $("#modal-book .modal-content").html(data.html_form);
      }
    });
  });

  $("#modal-stok").on("submit", ".js-stok-create-form", function () {
    var form = $(this);
    var data_id = form.attr("data-id");
    var url_action = '/supplier/' + data_id + '/new/';
    $.ajax({
      url: url_action,
      data: form.serialize(),
      type: form.attr("method"),
      dataType: 'json',
      success: function (data) {
        if (data.form_is_valid) {
          $("#stok-table tbody").html(data.html_stok_list);  // <-- Replace the table body
          $("#modal-book").modal("hide");
        }
        else {
          $("#modal-book .modal-content").html(data.html_form);
        }
      }
    });
    return false;
  });

});

函数$(“#modal-stok”)。on(“ submit”,“ .js-stok-create-form”,function())遇到了问题,我不知道如何传递{{ provider.pk}}保存后返回stok_list.html。

我的stok_list.html文件:

{% extends 'base2.html' %}

{% load static %}

{% block title %}
  {{ supplier.supplier }} - {{ block.super }}
{% endblock %}

{% block breadcrumb %}
  <li class="breadcrumb-item"><a href="{% url 'home' %}">Supplier</a></li>
  <li class="breadcrumb-item active">{{ supplier.supplier }}</li>
{% endblock %}

{% block javascript %}
  <script src="{% static 'js/stoks.js' %}"></script>
{% endblock %}

{% block content %}
  <div class="mb-4">
    <button type="button" class="btn btn-primary js-create-stok" data-id="{{ supplier.pk }}">
      <span class="glyphicon glyphicon-plus"></span>
      New book
    </button>
  </div>

  <table class="table" id="stok-table">
    <thead class="thead-dark">
      <tr>
        <th>#</th>
        <th>Stok</th>
      </tr>
    </thead>
    <tbody>
      {% for stok in supplier.stoks.all %}
        <tr>
          <td>{{ stok.pk }}</td>
          <td>{{ stok.stok }}</td>
        </tr>
      {% endfor %}
    </tbody>
  </table>

  <div class="modal fade" id="modal-stok">
    <div class="modal-dialog">
      <div class="modal-content">
      </div>
    </div>
  </div>
{% endblock %}

这是我的partial_create_stok.html文件:

{% load widget_tweaks %}

<form method="post" action="{% url 'new_stok' supplier.pk %}" class="js-stok-create-form" data-id="{{ supplier.pk }}" novalidate>
  {% csrf_token %}
  <div class="modal-header">
    <h4 class="modal-title">Create a new stok</h4>
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    {% for field in form %}
      <div class="form-group{% if field.errors %} has-error{% endif %}">
        <label>{{ field.label }}</label>
        {% render_field field class="form-control" %}
        {% for error in field.errors %}
          <p class="help-block">{{ error }}</p>
        {% endfor %}
      </div>
    {% endfor %}
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="submit" class="btn btn-primary">Create stok</button>
  </div>
</form>

这是我的urls.py文件:

from django.contrib import admin
from django.urls import path

from inventory import views

urlpatterns = [
    path('', views.home, name='home'),
    path('supplier/<int:pk>/', views.stoks, name='stoks'),
    path('supplier/<int:pk>/new/', views.new_stok, name='new_stok'),
    path('admin/', admin.site.urls),
]

这是我的模型。py:

from django.db import models

from django.contrib.auth.models import User


class Supplier(models.Model):
    supplier = models.CharField(max_length=30, unique=True)
    address = models.CharField(max_length=100)
    telephone = models.CharField(max_length=20)

    def __str__(self):
        return self.supplier


class Stok(models.Model):
    stok = models.CharField(max_length=30)
    supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, related_name='stoks')

    def __str__(self):
        return self.stok

服务器在控制台的日志错误如下所示:

  

django.db.utils.IntegrityError:NOT NULL约束失败:   stock_stok.supplier_id [11 / Mar / 2019 03:05:08]“发布   / supplier / 3 / new / HTTP / 1.1“ 500 16856

感谢您的帮助。

0 个答案:

没有答案