Home > database >  Image cannot be displayed after saving the data in Django. The code for it is given below
Image cannot be displayed after saving the data in Django. The code for it is given below

Time:12-01

Problem Statement: In shown image, default profile pic is visible but i need uploaded photo to be displayed here when i upload and saved in the database.I am using django framework.

What have I Tried here?

In setting.html file,The below is the HTML code for what is have tried to display image, bio, location. The problem may be at first div image tag. Though the default profile picture is visible but which i have uploaded is not displaying in the page nor able to save in database.

<form action="" method ="POST">
{% csrf_token %}
<div >
<div >
   <label for="">Profile Image</label>
   <img width = "100" height = "100" src="{{user_profile.profileimg.url}}"/>
   <input type="file" name='image' value = "" placeholder="No file chosen" >
</div>
<div >
   <label for="about">Bio</label>  
   <textarea id="about" name="bio" rows="3"  >{{user_profile.bio}}</textarea>
</div> 
<div >
   <label for=""> Location</label>
   <input type="text" name = "location" value = "{{user_profile.location}}" placeholder="" >
</div>
 </div> 
                                
 <div >
 <button > <a href="/"> Cancel</a> </button>
 <button type="submit" > Save </button>
 </div>
 </form>

In views.py file,the below function is the views file settings page logic for displaying the image, bio, location. If the image is not uploaded, it will be default profile picture. If image is not none then the uploaded image is displayed. But I am not getting what is the mistake here in my code.

@login_required(login_url='signin')
def settings(request):
    user_profile = Profile.objects.get(user = request.user)
    if request.method == "POST":
        if request.FILES.get('image')== None:
            image = user_profile.profileimg
            bio = request.POST['bio']
            location = request.POST['location']

            
        else:
            image = request.FILES.get('image')
            bio = request.POST['bio']
            location = request.POST['location']

        user_profile.profileimg = image
        user_profile.bio = bio
        user_profile.location = location
        user_profile.save()
        return redirect("settings")

    return render(request, 'setting.html', {'user_profile': user_profile})

I am expecting to know what the mistake in the code is. Only profileimg cannot be saved in database. the other data is able to save like bio, location.

The below is the model.py file.

from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()
# Create your models here.
class Profile(models.Model):
    user = models.ForeignKey(User, on_delete = models.CASCADE)
    id_user = models.IntegerField()
    bio = models.TextField(blank=True)
    profileimg = models.ImageField(upload_to = 'profile_images', default= 'blank-profile-picture.png')
    location = models.CharField(max_length = 100, blank = True)

    def __str__(self):
        return self.user.username

The below is the media folder in settings.py file.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',
]
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)

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

urls.py

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('core.urls')),
]   static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

Photo is not displaying. Photo is not displaying.

CodePudding user response:

You're trying to fetch the image in the wrong way.

Instead you can use this

src="/media/{{user_profile.profileimg}}"

If it doesn't work try removing "/" before media.

Please reply to this message if the issue still persist.

CodePudding user response:

Oh, Holy Shit. How could I miss it.

My friend problem is with view.

Add this thing to your function:

    if request.method == "POST" and "image" in request.FILES:

And while requesting for the image place the image only in the variable in list as given below.

        image= request.FILES['image']

I hope this should resolve. Please revert back if the issue still persist.

CodePudding user response:

Simply you can try this way:

<img width = "100" height = "100" src="/media/{{user_profile.profileimg}}"/>

And now that image will display

Note: If your uploaded image is saving in media folder then above code will work.

According to your model field profileimg, you should add forward slash to upload_to:

It must be like below:

upload_to='profile_images/'

And ensure that you have added this in your main urls:

urlpatterns = [

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

CodePudding user response:

Thank you for your answers. I found solution

<form action="" method ="POST" enctype = "multipart/form-data">

This enctype is missing in setting.html file. This works correctly and image displays correctly.

  • Related