简体   繁体   English

如何在 Django 中显示图像?

[英]How to display images in Django?

I have an inventory system.我有一个库存系统。 When I click a medicine, it shows this specific medicine's information.当我单击一种药物时,它会显示该特定药物的信息。 This page is medicine_details.html.这个页面是medicine_details.html。 When I open, I get all the correct information, but I cannot see the image.当我打开时,我得到了所有正确的信息,但我看不到图像。 When I open the page in inspect there is an error:当我在检查中打开页面时,出现错误:

<img src=(unknown) alt="img">

How can I fix it?我该如何解决?

views.py视图.py

def medicine_detail(request, id):
    medicine = get_object_or_404(Medicine, id=id)
    context = {
        'medicine': medicine,
    }
    return render(request, 'medicine_details.html', context)

models.py模型.py

class Medicine(models.Model):

    medicine_name = models.CharField(max_length=100)
    medicine_info = RichTextField(verbose_name="notes")
    medicine_code = models.CharField(max_length=100)
    medicine_qr = models.CharField(max_length=100)
    medicine_price = models.IntegerField()
    medicine_stock = models.IntegerField()
    medicine_image = models.ImageField(upload_to='images', null=True, blank=True)
    slug = models.SlugField(max_length=100, unique=True, editable=False)

    def get_image(self):
        if self.medicine_image and hasattr(self.medicine_image, 'url'):
            return self.medicine_image.url
        else:
            return

    def __str__(self):
        return self.medicine_name

    class Meta:
        ordering = ['medicine_name']

    def get_create_url(self):
        return reverse('medicines:medicine_create', kwargs={'slug': self.slug})

    def get_unique_slug(self):
        slug = slugify(self.slug.replace('ı', 'i'))
        unique_slug = slug
        counter = 1
        while Medicine.objects.filter(slug=unique_slug).exists():
            unique_slug = '{}-{}'.format(slug, counter)
            counter += 1
        return unique_slug

    def get_absolute_url(self):
        return reverse('medicines:medicine_create', kwargs={'slug': self.slug})

    def save(self, *args, **kwargs):
        self.slug = self.get_unique_slug()
        return super(Medicine, self).save(*args, **kwargs)

medicine_details.html医学详细信息.html

<div class="panel panel-primary">
                <div class="panel-heading text-center"><h3>{{medicine.medicine_name}} </h3></div>
                    <div class="panel-body">


                        <h4><p class="text-success">Medicine Name:  <small>{{medicine.medicine_name}}</small></h4>
                        <h4><p class="text-success">Details:  <small>{{medicine.medicine_info}}</small></h4>
                        <h4><p class="text-success">Barcode:  <small>{{medicine.medicine_code}}</small></h4>
                        <h4><p class="text-success">QR:  <small>{{medicine.medicine_qr}}</small></h4>
                        <h4><p class="text-success">Price:  <small>{{medicine.medicine_price}} TL</small></h4>
                        <h4><p class="text-success"> <small></small></h4>
                        <img src="{{ medicine.medicine_image.url }}" alt="img">

settings.py设置.py

... ...

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

urls.py ...网址.py ...

url(r'^medicines/(?P<id>\d+)/$', medicine_detail, name="detail"),


    ]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

I use MySQL for database management.我使用 MySQL 进行数据库管理。

Try it like this:试试这样:

{% if medicine.medicine_image %}
<img src="{{STATIC_URL}} {{ medicine.medicine_image.url }}" alt="img">
{% endif %}

In your settings file you should have:在您的设置文件中,您应该有:

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

If this doesn't work, please post what error you get.如果这不起作用,请发布您遇到的错误。

Replace {{ medicine.medicine_image.url }} with{{ medicine.medicine_image.url }}替换为

/media/{{ medicine.medicine_image.url }}

In your settings, set:在您的设置中,设置:

MEDIA_URL = '/media/'

ensure that django.template.context_processors.media in the context_processors option of TEMPLATES确保TEMPLATEScontext_processors选项中的django.template.context_processors.media

# settings
TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
         ...
        "OPTIONS": {
            ...
            "context_processors": [
                ...
                "django.template.context_processors.media",
            ],
        },
    }
]

then in your template, you can use:然后在您的模板中,您可以使用:

<img src="{{MEDIA_URL}}{{medicine.medicine_image}}" alt="img">

note: no backslash after {{MEDIA_URL}}注意: {{MEDIA_URL}}后没有反斜杠

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

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