如何从我的外键以Django形式获取价值

诺维拉尔

大家好,我是新来的,我现在正在学习django。抱歉,如果我的问题不够精确,但是我真的不知道该怎么称呼。这是我的代码:

库存/models.py

class Category(models.Model):
    name = models.CharField(max_length=40)

class Product(models.Model):
    category = models.ForeignKey(Category)
    sale_price = models.DecimalField(max_digits=8, decimal_places=2, default=0.00)
    #...

发票/models.py

from inventory.models import Product

class Invoice(models.Model):
    #...

class Row(models.Model):
    invoice = models.ForeignKey(Invoice)
    single_price = models.DecimalField(max_digits=8, decimal_places=2, default=0.00)
    #...

class InventoryRow(Row):
    product = models.ForeignKey(Product)
    def __unicode__(self):
        return self.product.name

发票/forms.py

class InvoiceForm(ModelForm):
    class Meta:
        model = Invoice

class InventoryRowForm(ModelForm):
    class Meta:
        model = InventoryRow
        fields = ('product')

发票/view.py

def invoice(request):
    TableFormSet = formset_factory(InventoryRowForm, extra=6)

    if request.method == 'POST':
        invoice_form = InvoiceForm(request.POST)
        table_formset = TableFormSet(request.POST)

        if invoice_form.is_valid() and table_formset.is_valid():
            invoice = invoice_form.save(commit=False)
            #...
            invoice.save()

            for form in table_formset.forms:
                t = form.save(commit=False)
                print t.product.sale_price
                t.single_price = t.product.sale_price
                t.invoice = invoice
                #...
                t.save()
            #From this place code doesn't execute

            return redirect('invoices:index')
    else:
        invoice_form = InvoiceForm()
        table_formset = TableFormSet()

    context = {
        'invoice_form': invoice_form,
        'table_formset': table_formset,
    }
    context.update(csrf(request))

    return render(request, 'invoices/invoice.html', context)

当我填写并发送表单时,出现HTTP错误500,异常类型:DoesNotExist和异常值:InventoryRow没有产品。调试模式还为我突出显示了分配为“ t.single_price = t.product.sale_price”的行,这让我感到惊讶,我可以将t.product.sale_price的值打印到控制台,它是正确的,并且保存了我的表格。有人知道为什么会这样吗?

Environment:

Request Method: POST
Request URL: http://192.168.0.104:8000/invoices/new/invoice

Django Version: 1.6.1
Python Version: 2.7.5
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'bootstrap_toolkit',
 'bootstrapform',
 'inventory',
 'invoices')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')


Traceback:
File "/Users/novirael/PythonEnvs/BMSEnv/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  114.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/novirael/PythonEnvs/BMSEnv/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  22.                 return view_func(request, *args, **kwargs)
File "/Users/novirael/PythonEnvs/BMSEnv/bms/invoices/views.py" in invoice
  74.                 t.single_price = t.product.sale_price
File "/Users/novirael/PythonEnvs/BMSEnv/lib/python2.7/site-packages/django/db/models/fields/related.py" in __get__
  324.                 "%s has no %s." % (self.field.model.__name__, self.field.name))

Exception Type: DoesNotExist at /invoices/new/invoice
Exception Value: InventoryRow has no product.
布莱恩·丹特

您只是进入表单集中的空表单。

您认为:

TableFormSet = formset_factory(InventoryRowForm, extra=6)

每次您点击此视图时,都会创建一个包含六个额外的表单的表单集。然后,在您的for循环的后面,对的调用form.save(commit=False)将不会返回InventoryRow带有关联Product对象的,因此DoesNotExist当您稍后尝试访问时会出现错误product.sale_price

您应该添加一个if以检查表单是否“绑定” [1]:

for form in table_formset.forms:
    if form.is_bound:
        t = form.save(commit=False)
        t.single_price = t.product.sale_price
        t.invoice = invoice
        #...
        t.save()

[1]此处提供有关“绑定表单”的更多信息:https : //docs.djangoproject.com/en/dev/ref/forms/api/#bound-and-unbound-forms

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Django(模型):如何从外键获取实例

来自分类Dev

Django获得外键的纯价值

来自分类Dev

如何使用Django形式的外键过滤选择值

来自分类Dev

如何以Django模型形式保存外键文本输入

来自分类Dev

Django如何根据以其他形式选择的父外键来过滤外键?

来自分类Dev

如何通过小村庄中的外键获取其他表的价值?

来自分类Dev

我如何获取cakephp当前模型的外键列名称?

来自分类Dev

如何获取对我的表有外键的表的列表?

来自分类Dev

如何从 django 模板获取视图中的外键?

来自分类Dev

Django:如何通过与外键相关的对象获取对象

来自分类Dev

从Django模板中的字典键获取价值

来自分类Dev

Django外键查询集形式

来自分类Dev

我无法使用 hql 获取外键

来自分类Dev

用作外键时,如何在Django Admin中更改用户表示形式?

来自分类Dev

Django从外键的类获取属性

来自分类Dev

Django模型外键获取属性

来自分类Dev

Django获取相关的外键字段混乱

来自分类Dev

从外键关系django获取ID

来自分类Dev

Django 在 Queryset 中获取外键对象

来自分类Dev

使用外键向后获取 django 对象

来自分类Dev

Django:获取外键的值而不是 id

来自分类Dev

Django Rest Framework,如何在另一个外键中获取外键的对象数量

来自分类Dev

我如何从单选按钮获取价值

来自分类Dev

我如何利用 jQuery 获取价值

来自分类Dev

如何获取外键的入门键值

来自分类Dev

如何获取外键的入门键值

来自分类Dev

如何从外键获取对象的值?

来自分类Dev

如何通过外键获取数据?

来自分类Dev

如何通过外键获取数据连接?