Search code examples
pythondjangopython-3.xsecurityimgur

python3 django cant load imgur images to html <img src...> if havent been open already manually


I am working on a project i python3 Django, it will test your knowledge from road-signs in Slovakia. A problem occurred when i stored all 300 signs images on Imgur. If i open firstly just image with a sign and than image inside of my HTML page everything works just fine, but i need to generate random images so i dn't know which one will be next one. Console in google chrome gives me 403 error code 'forbidden' also i can see in network tab of developer tools that it loads the image as txt/plain, which seems suspicious to me.

Can you help me somehow please?

Here is my html

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 

'app_signs/style.css' %}">
</head>
<body class="question">
  <form action="/question" method = "post">{% csrf_token %}
    <div class="container">
      <br>
      <img src="{{ right_sign.signurl }}" class="main_sign" alt="FOTKA">
      <br>
      <h3>Aka je to znacka?</h3>
      {% for sign in list%}
        <p>{{ sign }}<p>
      {% endfor %}
    </div>
  </form>
</body>

Here are views.py

from django.http import HttpResponse
from django.template import loader
from django.views.decorators.http import require_http_methods
from django.shortcuts import redirect

from app_signs.models import sign

import random


@require_http_methods(["GET", "POST"])
def question(request):
    if request.method == 'GET':
        rndint1 = '{:03}'.format(random.randint(1, 386))
        rndint2 = '{:03}'.format(random.randint(1, 386))
        rndint3 = '{:03}'.format(random.randint(1, 386))
        rndint4 = '{:03}'.format(random.randint(1, 386))

        right_sign = sign.objects.get(sign_id=rndint1)
        fake_sign1 = sign.objects.get(sign_id=rndint2)
        fake_sign2 = sign.objects.get(sign_id=rndint3)
        fake_sign3 = sign.objects.get(sign_id=rndint4)

        list_sign = [right_sign.sign_name,
                     fake_sign1.sign_name,
                     fake_sign2.sign_name,
                     fake_sign3.sign_name]

        random.shuffle(list_sign, random.random)

        template = loader.get_template('app_signs/question.html')
        return HttpResponse(template.render({'right_sign': right_sign,
                                             'list': list_sign}, request))

And here are models

from django.db import models


class sign(models.Model):
    sign_category = models.CharField(max_length=250)
    sign_id = models.CharField(max_length=4)
    sign_name = models.CharField(max_length=250)
    sign_url = models.CharField(max_length=250)

    def __str__(self):
            return self.sign_name

Solution

  • I finally found solution, it wasn't anything with python code. Trick was in changing 127.0.0.1 to localhost in url.