Django Inline formset with jquery

614 views
Skip to first unread message

Ajay Kumar

unread,
Feb 17, 2015, 12:01:02 AM2/17/15
to django...@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...

aRkadeFR

unread,
Feb 17, 2015, 3:44:46 AM2/17/15
to django...@googlegroups.com
Hello,

I got the same kind of probleme while working on the formset
couple days ago.

If this is related, the problem is the auto complete javascript that
doesn't go well with the jquery.formset.js.

You can add a function "added" in parameter of the formset function
for reloading the autocomplete widget.

something like:
```
    $(function() {
        $(".inline.{{ orderformset.prefix }}").formset({
            prefix: "{{ orderformset.prefix }}",
            added: function () { reload_auto_complete(); },
        })
    })

```

About the deletion, is it on the front end or the backend you're
talking about?

If this is front -> check your javascript
If this is backend -> check all the values dumping request.POST

Hope I was useful

Ajay Kumar

unread,
Feb 17, 2015, 5:16:09 AM2/17/15
to django...@googlegroups.com
Thank you so much for your reply.

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

By the above reference link at the bottom by  choosing Country Name the rest of the fields like Country Number , Country Phone code, Country code will be auto populated, like this i'm trying to achieve in django, In my above models, in  Order table when i give value to the serial_no the rest of the field's "name" and "author" should be autopulate. I achieved in one formset but unable to achieve in inline formset.


By the above image in the first record if i give value to serial_no the rest of fields "name" and "author" will get auto populate.But when i'm doing add another and tries to give value to  serial_no the auto populate is not working.I'm trying to achieve this in inline formset for each add another record like above reference link. Please if any idea suggest me.Thanks in advance.

--
You received this message because you are subscribed to a topic in the Google Groups "Django users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-users/lrmCMNq3Esw/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/54E2FF5F.2070509%40arkade.info.

For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages