Django 内联表单集添加另一个并删除

Django inline formset add another and remove

我正在尝试在 django 中构建此 link 功能, http://demo.smarttutorials.net/jquery-autocomplete/

此处选择 serial_no,其余字段名称和作者应自动填充。自动填充适用于第一个内联表单集并能够保存它,但是当我添加另一个内联表单集时自动填充不起作用而且我无法删除它或保存它。

models.py

from django.db import models

class Book(models.Model):
    serial_no = models.IntegerField(max_length = 100, unique = True)
    name = models.CharField(max_length = 50)
    author = models.CharField(max_length = 50)

    def __unicode__(self):
        return self.name

class CustomerOrder(models.Model):
    name = models.CharField(max_length=256)

    def __unicode__(self):
        return self.name

class Order(models.Model):
    customer  =  models.ForeignKey(CustomerOrder)
    serial_no = models.IntegerField(max_length = 100, unique = True)
    name = models.CharField(max_length = 50)
    author = models.CharField(max_length = 50)
    quantity = models.IntegerField(max_length = 100)

    def __unicode__(self):
        return self.name

forms.py

from django import forms
from bookapp.models import CustomerOrder


class CustomerOrderForm(forms.ModelForm):
    class Meta:
        model = CustomerOrder
        exclude = ('customer',)

views.py

from django.http import HttpResponse
from django.shortcuts import render
from bookapp.models import *
from bookapp.forms import CustomerOrderForm
import json
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.core.context_processors import csrf
from django.shortcuts import render_to_response, get_object_or_404
from django.forms.models import inlineformset_factory


def home(request):
    context =  RequestContext(request)
    OrderFormSet =   inlineformset_factory(CustomerOrder, Order  ,extra=1, exclude=('customer',))
    if request.method == "POST":
        customerorderform = CustomerOrderForm(request.POST)
        orderformset = OrderFormSet(request.POST)
        if customerorderform.is_valid() and orderformset.is_valid():
            a = customerorderform.save()
            orderformset.save(commit=False)
            orderformset.instance = a
            orderformset.save()
            return HttpResponse('Added')
    else:
        customerorderform = CustomerOrderForm()
        orderformset = OrderFormSet()
        for orderform in orderformset:
            orderform.fields['serial_no'].widget.attrs = {'id' : 'sno', 'onkeydown':"myFunction()"}
            orderform.fields['name'].widget.attrs = {'id' : 'bname'}
            orderform.fields['author'].widget.attrs = {'id' : 'bauthor'}

    args = {}
    args.update(csrf(request))
    args = {'customerorderform':customerorderform, 'orderformset':orderformset}
    return render_to_response('home.html',args,context)

def fetch_serial_nos(request):
    serial_nos = map(lambda x: str(x.serial_no), Book.objects.all())
    return HttpResponse(content = json.dumps({'serial_nos': serial_nos}), content_type = "application/json; charset=UTF-8")

def get_entry_corresponds_to_serial_no(request):
    serial_no = request.GET['serial_no']
    try: 
        entry = Book.objects.get(serial_no=int(serial_no))
        data = {'name': entry.name, 'author': entry.author}
    except (ObjectDoesNotExist, ValueError):
        data = {'name': '', 'author': ''}
    return HttpResponse(content = json.dumps(data), content_type = "application/json; charset=UTF-8")

home.html

<script src="{{ STATIC_URL }}js/min.js"></script>
<script src="{{ STATIC_URL }}js/jquery.formset.js"></script>


<p>Enter S.NO</p>
<script type="text/javascript">
    $(function() {
        $(".inline.{{ orderformset.prefix }}").formset({
            prefix: "{{ orderformset.prefix }}",
        })
    })
</script>
<body>
    <div>
        <h1>Orders</h1>
        <form action="/"  method="post">{% csrf_token %}
            <div>
                <legend>Customer</legend>
                {{customerorderform}}
            </div>
           <fieldset>
                <legend>Order</legend>
                {{ orderformset.management_form }}
                {{ orderformset.non_form_errors }}
                {% for form in orderformset %}
                    {{ form.id }}
                    <div class="inline {{ orderformset.prefix }}">
                        {{form}}
                    </div>
                {% endfor %}
            </fieldset>
            <input type="submit" value="Add order" class="submit" />
        </form>
    </div>
</body>
<p id="demo"></p>


<script>
$(function(){
    $.ajax({
        type: "GET",
        url: '/serial_nos/',        
        success: function (response) {
        serial_nos = response['serial_nos'];
        $( "#sno" ).autocomplete({
            source: serial_nos
         });
        },        
    });   
    });
function myFunction(){ 
    var sno = document.getElementById("sno").value;
    console.log(sno)
    document.getElementById("demo").innerHTML = "You selected: " + sno;
    $.ajax({
        type: "GET",
        url: '/entry/',
        data : {
            serial_no : sno,
        },        
        success: function (response) {
            console.log('success') 
            bname.value = response['name'];
            bauthor.value = response['author'];

        },        
    });
  }  
</script>

您的代码中存在多个问题。

  1. 您为多个 HTML 元素设置了相同的 ID,这是完全错误的。 ID的意义是唯一的。当您按 ID 搜索元素时,它将 return 只有一个(第一个匹配的元素)。
  2. 您仅在初始页面加载时初始化 autocmplete。相反,您需要为 formset javascript 创建的每个新行初始化它。这可以通过使用 formset 选项中配置的 added 回调来完成。在文档中查找详细信息 https://code.google.com/p/django-dynamic-formset/wiki/Usage#Formset_options

此外,我还有一些建议,希望您的代码在意识形态上更加正确。

  1. 不要使用 from module import *
  2. 重新排序您的导入(首先从标准库中导入,然后从框架中导入,最后从您的项目中导入)
  3. 请勿在 python 属性中设置 onkeydownonclick 等。为此使用 Javascript。 (这可能比前两个更重要)