Python Django某些静态图像未在模板中加载

时间:2018-12-10 06:09:25

标签: python django django-templates django-staticfiles django-static

我正在使用Django(1.10)开发一个项目,需要在Django模板中加载一些图像,但是我想知道有些图像正在加载但有些甚至没有加载,甚至存在于static_root文件夹中。

  

更新:我的项目目录中有两个目录assetsstatic_cdn,目前有2个产品,一个产品的图像显示,但不显示另一个,当我将此设置用作:

     

STATIC_ROOT = os.path.join(BASE_DIR, 'assets') STATIC_URL = '/assets/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_cdn'), ]   第一个产品的图像文件显示正确,但第二个产品的图像显示不正确。

     

但是:当我将此设置用作:   STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn') STATIC_URL = '/assets/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'assets'), ]

     

第二个产品的图像文件显示正确,但第一个产品的图像显示不正确。这真是令人困惑的一部分。

这是我的模特:

class AddedFile(models.Model):
    image_name = models.CharField(max_length=3000, blank=True, null=True)
    file_name = models.CharField(max_length=3000, blank=True, null=True)

    def __str__(self):
        return str(self.id)

class Products(models.Model):
    name = models.CharField(max_length=100, blank=True, null=True)
    description = models.TextField(max_length=200, blank=True, null=True)
    image = models.ForeignKey(AddedFile, on_delete=models.CASCADE, null=True)
    category = models.ForeignKey(Categories, on_delete=models.CASCADE, null=True)
    parent_product_id = models.IntegerField(null=True)
    product_type = models.CharField(max_length=100, blank=True)
    regular_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    sale_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    quantity = models.IntegerField(default=0)
    sku_no = models.CharField(max_length=100, blank=True, null=True)
    variant = models.CharField(max_length=100, blank=True, null=True)
    tax_able = models.BooleanField(default=False)
    enable_flag = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return str(self.id)

这里来自views.py

def product_add(request):
    user_type = ''
    try:
        user_type = request.session['user_type']
    except Exception as e:
        print(e)
    if user_type == 'admin':
        if request.method == "POST":
            try:
                cat_id = request.POST['cat_id']
                description = request.POST['description']
                img = request.POST['img']
                name = request.POST['name']
                product_type = request.POST['product_type']
                tax_able = request.POST['tax_able']

                if product_type == 'simple':
                    regular_price = request.POST['regular_price']
                    sale_price = request.POST['sale_price']
                    sku = request.POST['sku']
                    quantity = request.POST['quantity']
                    if img:
                        get_img = []
                        try:
                            directory_base = settings.STATIC_ROOT
                            image = img.split(";base64,")
                            extens = image[0]
                            ext = extens.split("/")
                            extension = ext[1]
                            base_image = image[1]
                            b_image = base64.decodestring(base_image)
                            time.sleep(0.5)
                            temp_name = str((time.time())).replace('.', '')
                            file_name = temp_name + '_product.' + extension
                            image_path = directory_base + '/product_image'
                            if os.path.isdir(image_path) is False:
                                os.makedirs(image_path)

                            file_path = image_path + "/" + file_name
                            print(file_path)
                            with open(file_path, 'wb') as f:
                                f.write(b_image)
                            get_img.append(file_path)
                            # Profile Pic Compression
                            pic = file_path
                            im = Image.open(pic)
                            # for icon on frontend
                            im = im.resize((int(math.floor(230)), int(math.floor(230))), Image.ANTIALIAS)
                            new_name = image_path + "/" + '230x230' + temp_name + "_product." + extension
                            try:
                                quality = 90
                                im.save(new_name, optimize=True, quality=quality)
                            except Exception as e:
                                ImageFile.MAXBLOCK = width * height
                                im.save(new_name, optimize=True, quality=quality)

                            # for thumbnais
                            im = im.resize((int(math.floor(50)), int(math.floor(50))), Image.ANTIALIAS)
                            new_name = image_path + "/" + '50x50' + temp_name + "_product." + extension
                            try:
                                quality = 90
                                im.save(new_name, optimize=True, quality=quality)
                            except Exception as e:
                                ImageFile.MAXBLOCK = width * height
                                im.save(new_name, optimize=True, quality=quality)

                            img_name = temp_name + "_product." + extension
                            addedfile_obj = AddedFile(image_name=str(img_name))
                            addedfile_obj.save()

                            if tax_able:
                                obj = Products(name=name, description=description, image_id=addedfile_obj.id,
                                               category_id=cat_id, product_type=product_type,
                                               regular_price=regular_price, sale_price=sale_price, quantity=quantity,
                                               sku_no=sku, tax_able=True)
                                obj.save()
                            else:
                                obj = Products(name=name, description=description, image_id=addedfile_obj.id,
                                               category_id=cat_id, product_type=product_type,
                                               regular_price=regular_price, sale_price=sale_price, quantity=quantity,
                                               sku_no=sku)
                                obj.save()
                            return HttpResponse(json.dumps({'success': 'Saved Successfully'}))
                        except Exception as e:
                            pass
                            return HttpResponse(json.dumps({'error': 'Some error occur'}))
                return HttpResponse(json.dumps({'error': 'Somethng went wrong'}))
            except Exception as e:
                print(e)

而且,这里是我如何加载模板:

def all_product(request):
    user_type = user_id = ''
    try:
        user_type = request.session['user_type']
        user_id = request.session['user_id']
    except Exception as e:
        pass
    if user_type == 'admin':
        all_products = ''
        try:
            all_products = Products.objects.filter(parent_product_id__isnull=True)
        # all_products=Products.objects.filter(product_type='simple');
        except Exception as e:
            pass
        return render(request, "all_products.html", {'all_products': all_products})

而且,这是设置:

STATIC_URL = '/static_cdn/'
STATICFILES_DIRS = (
    'static',
)
STATIC_ROOT = "static_cdn"


MEDIA_URL = "/media/"
MEDIA_ROOT = "media_cdn/"
EMAIL_URL = "137.27.76.49/dashboard/"
ENCODE_KEY = 'This_is_my_awsome_secret_key'
GROCERY_ITEMS_PER_PAGE = 10

# DATA_UPLOAD_MAX_MEMORY_SIZE = 52428800
SESSION_SAVE_EVERY_REQUEST = False

并且,这是我要加载这些图像的模板:

{% for product in all_products %}
                <div class="col-sm-6 col-md-4 col-xs-6">
                  <div class="product_grid text-center">
                    <a class="" href="{% url 'single_page' id=product.id %}">
                      <div class="pro_grid_img d_table">
                        <div class="d_table_cell">
                          <img src="{% static 'product_image/' %}{{product.image.image_name}}" alt="No image">
                        </div>
                      </div>
                    </a>
                </div>
           </div>
{% endfor %}

这里是一个URL,用于查看正在加载某些图像但未加载其他图像的页面:http://c2f886fa.ngrok.io/grocery_order

所有图像均已上传到sttaic_cdn/product_image文件夹中。

这有什么问题吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

我认为您的代码中有一些错别字。 例如,主页上的第[14]行:

<link rel="shortcut icon" href="{% static 'frontend/images/fev.png" type="image/x-icon" />

应更改为:

<link rel="shortcut icon" href="{% static 'frontend/images/fev.png' %}" type="image/x-icon" />

您可能会忘记结束static模板标记。