Django inlineformset autocomplete and autopopulate by ajax

2015-02-12 Thread Ajay Kumar


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

Here by choosing country the rest of the fields will be auto populated, 
like this i'm trying to achieve in django, If any idea pls tell me it will 
be very great for me


This is Product table,by this i will add many products
*models.py*
class Product(models.Model):
 store = models.ForeignKey(Store)
 code = models.CharField(verbose_name='Product Code', max_length=128, 
blank=False)
 name = models.CharField(verbose_name='Product Name', max_length=128, 
blank=False)
 unit_price = models.FloatField(verbose_name='Unit Price', blank=False)
 in_stock = models.IntegerField(verbose_name='In Stock', default=0, 
blank=False)


This is Invoice order table, in this i will get customer details
class Invoice(models.Model):
 customer = models.ForeignKey(Customer)
 date = models.DateTimeField(auto_now=True, blank=False)


This in Invoice Item order table which is in inline formset 
class InvoiceItem(models.Model):
 invoice = models.ForeignKey(Invoice)
 product = models.ForeignKey(Product)
 particular = models.CharField(verbose_name='Particular', max_length=128
, blank=False)
 quantity = models.IntegerField(verbose_name='Quantity', default=0)
 unit_price = models.FloatField(verbose_name='Unit Price', blank=False)
 tax_rate_percentage = models.FloatField(verbose_name='Tax Rate 
Percentage', blank=False)

*views.py*
I'm trying to raise invoice by autopopulate feature.
def add_invoice(request):
  store = Store.objects.get(id=pk)
  product = Product.objects.filter(store=store)
  context =  RequestContext(request)
  InvoiceItemInlineFormSet = inlineformset_factory(Invoice, InvoiceItem, 
extra = 1,exclude=('invoice',))
  if request.method == 'POST':
invoiceform = InvoiceForm(request.POST)
invoiceformset =  InvoiceItemInlineFormSet(request.POST)
if invoiceform.is_valid() and invoiceformset.is_valid():
   invoice = invoiceform.save(commit=False)
   invoice.store = store
   invoice.save()
   invoiceformset.save(commit=False)
   invoiceformset.instance = invoice
   invoiceformset.save()
   return HttpResponseRedirect('/store_invoice/%s/invoice/'% pk)
   else:
  invoiceform = InvoiceForm()
  invoiceformset =  InvoiceItemInlineFormSet()
   args = {}
   args.update(csrf(request))
  args = {'email':email,'store':store,'invoiceform':invoiceform, 
'invoiceformset':invoiceformset}
  return render_to_response('invoice/invoice_add.html',args,context)


*invoice_add.html*

{% extends "base_site.html" %}
{% load staticfiles %}
{% block title %}Add New Order | Finvoicez{% endblock %}
{% block page-heading %}Add New Order{% endblock %}
{% block content %}


$(function() {
$(".inline.{{ invoiceformset.prefix }}").formset({
prefix: "{{ invoiceformset.prefix }}",
})
})


{% 
csrf_token %}


Customer
{{invoiceform}}



Order Items
{{ invoiceformset.management_form }}
{{ invoiceformset.non_form_errors }}
{% for form in invoiceformset %}
{{ form.id }}

{{form}}

{% endfor %}

Add Order


{% endblock %}


Here i'm trying to bring when i'm adding Invoice Item , by selecting the 
product code the rest of fields want to be autopopulate by corresponding 
Product details(Particular,unit price and tax) and it must be in 
inlineformset, for every 'add another' it must be autopopulate, like above 
reference link.
thanks in advance



-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@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/bdab6549-0749-4ec4-8f67-c85a93cd5c2a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Django Inline formset with jquery

2015-02-16 Thread Ajay Kumar


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




Enter S.NO

$(function() {
$(".inline.{{ orderformset.prefix }}").formset({
prefix: "{{ orderformset.prefix }}",
})
})



Orders
{% csrf_token %}

Customer
{{customerorderform}}

   
Order
{{ orderformset.management_form }}
{{ orderformset.non_form_errors }}
{% for form in orderformset %}
{{ form.id }}

{{form}}

{% endfor %}









$(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 = respo

The inline foreign key did not match the parent instance primary key.

2015-05-09 Thread Ajay Kumar
I'm trying to set custom id for my model,

*models.py*

from django.db import models
import uuid


def get_ref_id():
 ref_id = str(uuid.uuid4())[:11].replace('-','').lower()
 try:
 id_exists = Sample.objecsts.get(ref_id = ref_id)
 get_ref_id()
 except:
 return ref_id


class Sample(models.Model):
 ref_id = models.CharField(max_length = 128, primary_key = True, default=
get_ref_id)
 email = models.EmailField(max_length=128,unique=True)


 def __unicode__(self):
 return self.email


class MobileNumber(models.Model):
 sample = models.ForeignKey(Sample)
 mobile_number = models.CharField(max_length=128)


*admin.py*
















*from django.contrib import adminfrom sample.models import Sample, 
MobileNumberclass MobileNumberInline(admin.StackedInline): model = 
MobileNumber extra = 1class SampleAdmin(admin.ModelAdmin): inlines = 
[MobileNumberInline]admin.site.register(Sample,SampleAdmin)*





When i try to insert a record from admin it shows the error, But when i 
tried only with parent table it works.When i came to add child table its 
not working.Its just shows "Please correct the error below".And then i 
tried to save through userinterface views(out of admin) it shows the 
following error "The inline foreign key did not match the parent instance 
primary key". 





-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@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/854f71c8-2b21-4184-a533-497f39b236d6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Django inline formset(UI) delete/remove

2015-05-11 Thread Ajay Kumar
I'm trying to do a inline formset with UI not with dajngo built in 
inlineformset_factory form.Here i'm done with add_view and edit_view.Here 
in the edit view i can update the existing record for the both parent and 
child model,and can add new record to the child model.But i cant remove the 
existing record from the child model in inline formset.Every thing is fine 
working at client side.When i click remove button from the UI, the record 
is removed by javascript,But in server side, in the edit_view the #Delete 
Existing record block cloud take the delete/remove functionality.I tried in 
many possible ways but i can't make the delete query for the removed items 
form the client side.

*models.py*

from django.db import models
class Category(models.Model):
name=   models.CharField(max_length=128)

def __unicode__(self):
return self.name
class Product(models.Model):
category=   models.ForeignKey(Category)
name=   models.CharField(max_length=128)
price   =   models.CharField(max_length=128)



views.py

def add(request):
context =  RequestContext(request)
if request.method == 'POST':
category = Category.objects.create(name = request.POST['category'])
try:
for n in range(1,7):
product = Product.objects.create(category= 
category,name=request.POST['name_'+str(n)],price=request.POST['price_'+str(n)])
except KeyError:
pass
return HttpResponseRedirect('/')
return render_to_response('add.html',context)
def edit(request,pk):
category = get_object_or_404(Category,id=pk)
product = Product.objects.filter(category=category)
product_count = product.count()
context =  RequestContext(request)
if request.method == 'POST':
for c in Category.objects.filter(id = category.id):
c.name = request.POST['category']
c.save()
try:
#Update Existing record(child)
for p,n in zip(Product.objects.filter(category = c),range(1,7)):
p.name = request.POST['name_'+str(n)]
p.price = request.POST['price_'+str(n)]
p.save()
except KeyError:
#Delete Existing record(child)
try:
for d in range(1,7):
for i in 
Product.objects.all().filter(name=request.POST.get('name_'+str(d)),price=request.POST.get('price_'+str(d))):
print i.name

except KeyError:
pass
else:
#Add new record(child)
try:
for r in range(1,7):
product,created = 
Product.objects.update_or_create(category= 
category,name=request.POST['name_'+str(r)],price=request.POST['price_'+str(r)])
except KeyError:
pass
return HttpResponseRedirect('/')
args = {'category':category,'product':product,'product_count':product_count}
return render_to_response('edit.html',args,context)




add.html

Add
var i = 1;
function addProduct(){
if (i <= 5){
i++;
var div = document.createElement('div');
div.innerHTML = 'Name:Price:';
document.getElementById('products').appendChild(div);
}}

function removeProduct(div) {   
document.getElementById('products').removeChild( div.parentNode );
i--;}
{% csrf_token %}
Category



Product

(limit 6)
Name:Price:









edit.html

Edit
var i = {{product_count}};

function addProduct(){
if (i <= 5){
i++;
var div = document.createElement('div');
div.innerHTML = 'Name:Price:';
document.getElementById('products').appendChild(div);
}}

function removeProduct(div) {   
document.getElementById('products').removeChild( div.parentNode );
i--;}
{% csrf_token %}
Category



Product



(limit 6)
{% for list in product %}

Name:Price:

{% endfor %}









-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/dja

Django simple Captacha

2016-07-19 Thread Ajay Kumar


hi Guys

I tried django-simple-captcha on refering 
http://django-simple-captcha.readthedocs.io/…/la…/usage.html 
. Every 
thing works well and goes fine, I need few suggestion on it.

1. How efficiency is this?
2. How strong is this?
3. How easy/hard to cark this captcha?
4. Can we use this to high end applications?

Guys please suggest me for above line items or any this else there please 
let me know about django-simple-captcha, please explain me the pros and 
cons of django-simple-captcha. Thanks in advance.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/58b761a7-98eb-4105-a469-2735f49a0be6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


customise list editable based on user group in django-admin

2016-11-10 Thread Ajay Kumar
I have two types of users - 1 superuser and 2 support user
I need to customise list_editable so that only superuser can edit and 
support user can only view that field in django-admin interface.
Please let me know which function do I need to override and how to do this.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/a207521a-0539-48d1-b1ec-72696265391c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.