简体   繁体   English

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

[英]Python Django Some static images are not loading in Templates

I'm working on a project using Django(1.10) in which I need to load some images in Django templates, But I'm wondering some images are loading but some are not loading even exists in the static_root folder. 我正在使用Django(1.10)开发一个项目,需要在Django模板中加载一些图像,但是我想知道有些图像正在加载,但有些甚至没有加载到static_root文件夹中。

Update: I have two directories in my project dir, assets and static_cdn and have 2 products at the moment, the image for one product is showing but not for other one, When I have used this setting as: 更新:我的项目目录中有两个目录, assetsstatic_cdn ,目前有2种产品,一种产品的图像正在显示,而另一种产品则没有,当我将此设置用作:

STATIC_ROOT = os.path.join(BASE_DIR, 'assets') STATIC_URL = '/assets/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_cdn'), ] The image file for the first product displays correctly but not the image of the second product. STATIC_ROOT = os.path.join(BASE_DIR, 'assets') STATIC_URL = '/assets/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_cdn'), ]第一个产品的图像文件正确显示,但第二个产品的图片。

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

The image file for the second product displays correctly but not the image of the first product. 第二个产品的图像文件显示正确,但第一个产品的图像显示不正确。 that's really confusing part. 那真是令人困惑的一部分。

Here are my models: 这是我的模型:

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)

Here's from views.py : 这是来自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)

And, here how I'm loading the template: 而且,这里是我如何加载模板:

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})

And, here is the settings: 并且,这是设置:

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

AND, here is the templates where I'm loading these images: 而且,这是我要加载这些图像的模板:

{% 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 %}

Here's a URL to look at the page which is loading some images but not loading others: http://c2f886fa.ngrok.io/grocery_order 这是查看正在加载某些图像但未加载其他图像的页面的URL: http : //c2f886fa.ngrok.io/grocery_order

All of the images have uploaded into the sttaic_cdn/product_image folder. 所有图像都已上载到sttaic_cdn/product_image文件夹中。

What can be wrong here? 这里有什么问题?

Thanks in advance! 提前致谢!

I think there is some typos in your code. 我认为您的代码中有一些错别字。 For example, line[14] in your main page: 例如,主页上的第[14]行:

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

this should be changed to: 这应该更改为:

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

You might forget to end the static template tag. 您可能会忘记结束static模板标记。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM