【问题标题】:Django keeps returning local variable 'product' referenced before assignment errorDjango不断返回分配错误之前引用的局部变量“产品”
【发布时间】:2019-09-10 20:05:37
【问题描述】:

我在我的 django 模型中存储了一个产品列表,每个产品附加了多个图像作为外键。我正在尝试在我的 django 视图中检索所有产品及其各自的图像,以便我可以在屏幕上打印它们。但是,无论我做什么,我都会在赋值错误之前不断获取局部变量“产品”引用。

Models.py:
   class product(models.Model):
    title = models.CharField('', max_length=100,  db_index=True)
    price = models.CharField('', max_length=100,  db_index=True)
    description = models.CharField('', max_length=100,  db_index=True)

   class productimage(models.Model):
    product = models.ForeignKey(product, on_delete=models.CASCADE)
    product_images = models.FileField(blank=True)


views.py:
from django.shortcuts import render
from selling.models import product
from selling.models import productimage
from django.shortcuts import redirect
from django.template import loader

template = loader.get_template("selling/shop.html")
    if product.objects.exists():
        products = product.objects.all()
        for product in products:
            productimages = product.productimage_set.all()
            for productimage in productimages:
                imageurl = productimage.product_image.url
            context = {
                    "products" : products,
                    "productimages" : productsimages,
                }

【问题讨论】:

  • 在 Django 中,模型类以大写字母开头是一个非常严格的约定。如果您在此处遵循此操作,您可能会更早注意到您的错误。

标签: python django view model


【解决方案1】:

您可以使用不同的名称导入产品(或)更改变量名称。 喜欢 from selling.models import product as product_model 所以在其余的代码中你可以使用product_model。这应该消除所有混乱,因此你不应该有任何问题。

【讨论】:

    【解决方案2】:

    我认为您忘记在视图中导入产品。所以像这样更新你的代码:

    from .models import product   # use camel case when writing class name
    

    另外,你的实现在视图中有点复杂(循环遍历产品和产品图像)。您可以像这样将它们中的大部分移动到模板中:

    template = loader.get_template("selling/shop.html")
    products = product.objects.all()
    if products.exists():
        context = {
                "products" : products,
        }
    

    模板:

    {% for product in products %}
         {% for product_image in product.productimage_set.all %}
             <img src="{{product_image.product_image.url}}">
         {% enfor %}
    {% endfor %}
    

    【讨论】:

    • 我在视图顶部导入了产品。我已将其添加到视图中以反映这一点
    • 我认为 Python 很困惑,因为它看到你有一个局部变量 productfor 循环内的变量,依次分配给 products 的每个元素) -因此认为if product.objects.exists() 正在引用它(在它被分配之前,因此出现错误)。尝试为循环变量使用不同的名称(尽管我同意 product 是最自然的名称 - 正如我之前在评论中所说,最好的解决方法是将模型名称改为 Product)。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多