Django Inline formset with jquery and auto populate

58 views
Skip to first unread message

Ajay Kumar

unread,
Feb 17, 2015, 12:07:11 AM2/17/15
to djang...@googlegroups.com

Hello all,

I'm trying to build this following link feature in django, http://demo.smarttutorials.net/jquery-autocomplete/

Here by choosing serial_no and the rest of the fields name and author should be auto populate. Auto populate works for first inline formset and able to save it but when I add another inline formset auto populate is not working plus I'm unable to delete it or save it.

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>



Thanks in advance...
Reply all
Reply to author
Forward
0 new messages