0

I have an inventory system. When I click a medicine, it shows this specific medicine's information. This page is 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

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

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

<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

...

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

urls.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.

MeL
  • 1,269
  • 3
  • 12
  • 30
eda
  • 31
  • 6

3 Answers3

0

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.

MeL
  • 1,269
  • 3
  • 12
  • 30
  • It does not work but it show the ALT text and left of it there is a broken picture icon – eda Jun 27 '20 at 22:01
  • Do you have `{% load static % }` on the top of your page? – MeL Jun 27 '20 at 22:28
  • Yes. For example when I add image from admin panel, I quit from that page and open again the image is dissapear like I never added it. – eda Jun 27 '20 at 22:32
  • I wrote wrong something in urls.py I fixed it and edited my question now when I add image from admin panel I get an error: expected str, bytes or os.PathLike object, not tuple – eda Jun 27 '20 at 23:07
  • Make sure there is no comma after your BASE_DIR. You must have an extra comma somewhere, because it is picking something up as a tuple that shouldn't be one. – MeL Jun 27 '20 at 23:15
  • Yes I fixed it but still don't work. :( I guess I should write all over again. – eda Jun 28 '20 at 12:31
0

Replace {{ medicine.medicine_image.url }} with

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

Kareem
  • 569
  • 2
  • 18
0

In your settings, set:

MEDIA_URL = '/media/'

ensure that django.template.context_processors.media in the context_processors option of TEMPLATES

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

minglyu
  • 2,958
  • 2
  • 13
  • 32
  • @eda have you changed the image name?, b'img_medicine/apranax_3ISERzD.jpg' is `bytes` not `str` – minglyu Jun 28 '20 at 19:05
  • I changed medicine name as 0.jpg and I get error: [28/Jun/2020 22:11:17] "GET /medicines/6/ HTTP/1.1" 200 2950 Not Found: /media/b'img_medicine/0_Ga1GI77.jpg' – eda Jun 28 '20 at 19:12
  • it seems that you somehow breaks the normal storage behavior, the file path should never be a `bytes` object, if it is `bytes` object, you could not save the image in first place. – minglyu Jun 28 '20 at 19:15
  • I use mysql database and I made medicine_image is blob. Is it okey or not? – eda Jun 28 '20 at 19:24
  • it's much easier and advisable to use file system for storage though – minglyu Jun 28 '20 at 19:29
  • @eda if its `blob`, you can have a look of this question https://stackoverflow.com/questions/31358578/display-image-stored-as-binary-blob-in-template. BTW, you need to read the content of the file and save as blob, but not the path(name) as binary – minglyu Jun 28 '20 at 19:40