Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

271
Visualizações
Django: how can i display an image from the django database on a template based on an selected option from a form?

I am a beginner with django and I have been struggling for a few weeks to correlate a user's selected option in a form with the data in my database to list the logo of the selected brand and the car model image in the template.

So far I have managed to bring and store the data from the selected form in the database (MasinaSelectata model), the data is updated according to the client's ip.

Now I need to use the data stored in the (MasinaSelectata model) and list the brand logo in the (Constructor model) and the model image in the (Model model). Which I fail to do due to lack of experience and knowledge.

I tried several variants, none of them succeeded, my last attempt is the one below.

Models:

class Constructor(models.Model):
constructor_nume    = models.CharField(max_length=100, unique=True)
slug                = models.SlugField(max_length=150, unique=True)
logo_constructor    = models.ImageField(upload_to='photos/selectormasina', blank=True)

class Model(models.Model):
constructor         = models.ForeignKey(Constructor, on_delete=models.CASCADE)
model_nume          = models.CharField(max_length=200, unique=True)
slug                = models.SlugField(max_length=250, unique=True)
imagine_model       = models.ImageField(upload_to='photos/selectormasina', blank=True)

class Versiune(models.Model):
constructor         = models.ForeignKey(Constructor, on_delete=models.CASCADE)
model               = ChainedForeignKey(Model, chained_field="constructor", chained_model_field="constructor",
    show_all=False,
    auto_choose=True,
    sort=True)
versiune_nume       = models.CharField(max_length=300, unique=True)
slug                = models.SlugField(max_length=350, unique=True)

class MasinaSelectata(models.Model):
constructor = models.ForeignKey(Constructor, on_delete=models.CASCADE)
model       = models.ForeignKey(Model, on_delete=models.CASCADE)
versiune    = models.ForeignKey(Versiune, on_delete=models.CASCADE)
clientip    = models.CharField(max_length=20)

Views.py:

def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
    ip = x_forwarded_for.split(',')[0]
else:
    ip = request.META.get('REMOTE_ADDR')
return ip   

def logo(request):
ip = get_client_ip(request)
select = MasinaSelectata.objects.filter(clientip = ip)
context = { 'select': select}
return render(request, 'navbar.html', context)

Templates: navbar.html

<div class="col-lg-2 col-md-3 col-6 ">
 <!-- logo marca-->
 <div class="img-fluid">
 <img src="{{ select.constructor.logo_constructor.url }}" alt="{{select.logo.constructor.constructor_nume.url}}"></div>
</div>

I researched django documentation, google, youtube, and SO but I don't seem to have found a solution. I'm sure it's something I'm missing so please help me.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I finally managed to find a solution:

Views.py:

to show the selected manufacturer's logo

def get_imagine_constructor_data(request, *args, **kwargs):
selected_constructor = kwargs.get('producator')
img_constructor = 
list(Constructor.objects.filter(constructor_nume=selected_constructor).values())
return JsonResponse({'data':img_constructor})

to show the image of the selected model

def get_imagine_model_data(request, *args, **kwargs):
selected_model = kwargs.get('model')
img_modele = list(Model.objects.filter(model_nume=selected_model).values())
return JsonResponse({'data':img_modele})

Url.py

path('imagine-masina-json/<str:model>/', views.get_imagine_model_data, 
name='imagine-masina-json'),

path('imagine-constructor-json/<str:producator>/', 
views.get_imagine_constructor_data, name='imagine-constructor-json'),

I used a script to correlate the data in the database with the choices made by the client and show the images corresponding to the selections. For me it was easier this way.

Templates: navbar.html

<div class="img-fluid" id="imagine-constructor" ></div>
<div class="img-fluid" id="imagine-model" ></div>

const imagineDataBox = document.getElementById('imagine-model')
const imagineConstructorDataBox = document.getElementById('imagine-constructor')

for manufacturer's logo

imagineConstructorDataBox.innerHTML = ""
    $.ajax({
        type: 'GET',
        url: `imagine-constructor-json/${selectedConstructor}/`,
        success: function(response){
            console.log(response.data)
            const logo = response.data
            logo.map(item=>{
                const option = document.createElement('img')
                option.textContent = item.constructor_nume
                option.setAttribute('src', `media/${item.logo_constructor}`)
                option.setAttribute('alt', item.constructor_nume)
                option.setAttribute('style', 'max-height: 150px;')
                option.setAttribute('class', 'img-fluid')
                imagineConstructorDataBox.appendChild(option)
            })
        },
        error: function(error){
            console.log(error)
        },
    })

for model image:

imagineDataBox.innerHTML = ""
    $.ajax({
        type: 'GET',
        url: `imagine-masina-json/${selectedModel}/`,
        success: function(response){
            console.log(response.data)
            const logo = response.data
            logo.map(item=>{
                const option = document.createElement('img')
                option.textContent = item.model_nume
                option.setAttribute('src', `media/${item.imagine_model}`)
                option.setAttribute('alt', item.model_nume)
                option.setAttribute('style', 'max-height: 200px;')
                imagineDataBox.appendChild(option)
            })
        },
        error: function(error){
            console.log(error)
        },
    })

I hope it will be useful for someone else who will run into this problem.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda