Home > database >  djano - can not display an uploaded image from mySQL database
djano - can not display an uploaded image from mySQL database

Time:06-04

I configured everything as it should and yet I can't display the images from my database.

settings.py :

STATIC_URL = '/static/'
MEDIA_URL = '/media/'

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

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

models.py

class Etudiants(models.Model):
    numeroetudiant = models.BigIntegerField(db_column='numeroEtudiant', blank=True, null=True)  # Field name made lowercase.
    nom = models.CharField(max_length=255, blank=True, null=True)
    prenom = models.CharField(max_length=255, blank=True, null=True)
    groupe = models.BigIntegerField(blank=True, null=True)
    photo = models.ImageField(blank=False, null=False, upload_to='images/')
    email = models.CharField(max_length=255, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'etudiants'

    def __str__(self):
        return self.nom   " "   self.prenom

views.py :

def ajoutetudiant(request): 
    submitted = False
    if request.method == "POST":
        form = EtudiantsForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("../ajoutetudiant/")
    else: 
        form = EtudiantsForm()
        if 'submitted' in request.GET:
            submitted = True
    
    return render(request, 'ajoutetudiant.html', {'form': form})

urls.py (of my project) :

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('notes.urls')),
]  static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

.html :

<img src="{{etudiant.photo.url}}"/>

The pictures are saved in my database as you can see here. But cannot display it. as you can see here

My field in mySQL database is "blob". If it shouldn't be blob what should i put ? imagesql

CodePudding user response:

Your MySQL field for photo should be:

`photo` varchar(100) NOT NULL,
  • Related