保存django模型实例时出错。但是如果没有保存,那么代码片段就可以工作了

时间:2016-04-20 18:42:34

标签: django django-models django-views

这是我的django views代码段:

if (calltype == 'save'):
        bill_data = json.loads(request.POST.get('bill_details'))
        Invoice=salesInvoice()
        customerkey = request.POST.get('customer')
        Invoice.customer_key = Customer.object.get(key__iexact=customerkey)
        Invoice.total = request.POST.get('total')
        Invoice.grand_discount = request.POST.get('grand_discount')
        Invoice.amount_paid = request.POST.get('amount_paid')
        #Invoice.save()

        #saving the salesLineItem and linking them with foreign key to invoice
        for data in bill_data:
            LineItem = salesLineItem()
            #LineItem.invoice_no = salesInvoice
            itemcode=data['itemCode']
            LineItem.name = Product.object.get(key__iexact=itemcode).name
            LineItem.unit = Product.object.get(key__iexact=itemcode).unit
            LineItem.batch = Product.object.get(key__iexact=itemcode).batch
            LineItem.discount1 = Product.object.get(key__iexact=itemcode).discount1
            LineItem.discount2 = Product.object.get(key__iexact=itemcode).discount2
            LineItem.quantity = int(data['itemQuantity'])
            LineItem.free = int(data['itemFree'])
            LineItem.mrp = Product.object.get(key__iexact=itemcode).mrp
            LineItem.selling_price = Product.object.get(key__iexact=itemcode).selling_price
            LineItem.vat_type = Product.object.get(key__iexact=itemcode).vat_type
            LineItem.vat_percent = Product.object.get(key__iexact=itemcode).vat_percent
            #LineItem.save()
        #this part is just for checking
        response_data['name'] = Product.object.get(key__iexact=itemcode).name

请注意,我已注释掉用于保存发票和lineitem的行。一旦我取消注释这些行,我得到的错误是:

name 'Invoice' is not defined

我还覆盖了django模型的save方法(对于salesInvoice模型)。以下是它的代码(在django模型文件中),在注释行中,我对它的作用有一个小解释:

#the save method is overriden to give unique invoice ids, slug and customer_name
def save(self, *args, **kwargs):
    today = dt.date.today()
    today_string = today.strftime('%y%m%d')
    next_invoice_number = '01'
    last_invoice = Invoice.objects.filter(invoice_id__startswith=today_string).order_by('invoice_id').last()
    if last_invoice:
        last_invoice_number = int(last_invoice.invoice_id[6:])
        next_invoice_number = '{0:03d}'.format(last_invoice_number + 1)
    self.invoice_id = today_string + next_invoice_number
    if not self.id:
        self.slug=slugify(self.invoice_id)
        customer_name = Customer.object.get(key__iexact=customer_key).name
        address = Customer.object.get(key__iexact=customer_key).address
    super(Invoice, self).save(*args, **kwargs) 

我不明白错误在哪里。 任何帮助将不胜感激。

编辑1 - 添加追溯

Traceback:
File "C:\Users\Ganguly PC\Desktop\DjangoStudy\my_env\lib\site-packages\django\core\handlers\base.py" in get_response
  132.                     response = wrapped_callback(request,  *callback_args, **callback_kwargs)
File "C:\Users\Ganguly PC\Desktop\DjangoStudy\billinv\billbrain\views.py" in salesinvoice
  173.          Invoice.save()
File "C:\Users\Ganguly PC\Desktop\DjangoStudy\billinv\billbrain\models.py"   in save
  189.      last_invoice =         Invoice.objects.filter(invoice_id__startswith=today_string).order_by('invoice_id').last()

Exception Type: NameError at /master/salesinvoice/
Exception Value: name 'Invoice' is not defined
Request information:
GET: No GET data

POST:
amount_paid = '0.00'
customer = 'fr'
csrfmiddlewaretoken = 'xxxxxxxxxxxxxxxxxxxxx'
bill_details = '[{"itemCode":"rev","itemQuantity":"5","itemFree":"0"}]'
grand_discount = '0.00'
total = '435.00'
calltype = 'save'

1 个答案:

答案 0 :(得分:1)

你的追溯中显而易见。第173行调用Invoice.save()然后转到您覆盖的save()方法。然后显示行189并告诉您发生错误的最近位置:您正在执行:

last_invoice = Invoice.objects.filter(invoice_id__startswith=today_string).order_by('invoice_id').last()

Invoice未定义。它更像是一个蟒蛇问题,而不是一个django问题。您需要首先定义类名,然后使用它。在视图中您执行了import Invoice,但在此处您无法做到,但您可以使用type(self)来引用该实例。所以:

last_invoice = type(self).objects.filter(invoice_id__startswith=today_string).order_by('invoice_id').last()