Search code examples
pythondjangodjango-media

Image is not getting saved in the database django


I am trying to upload an image to the database. While posting the data I am not getting any error.

input for the image

<div class="text-center">
  <h6>Upload a different photo...</h6>
      <input type="file" class="form-control" name="user_img">
</div>

model with the image

class UserProfile (models.Model):
    user_img = models.ImageField(null=True, blank=True, upload_to='static/images')
    ...

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('colos.urls')),
    path('accounts/', include('allauth.urls')),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

settings.py

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

views.py

def edit_profile(request):
    try:
        # checking if the user exist in UserProfile through the logged in email id
        user_data = UserProfile.objects.get(emailID = request.user.email)
        if request.POST.get('action') == 'post' and request.FILES:
            name = UserProfile.objects.all()
            response_data = {}
            # user profile image start
            user_img = request.FILES['user_img']
            # user profile image end
            name = request.user.username
            emailID = request.user.email
            phone = request.POST.get('phone')
            college_name = request.POST.get('college_name')
            branch = request.POST.get('branch')

            response_data['user_img'] = user_img
            response_data['name'] = name
            response_data['emailID'] = emailID
            response_data['phone'] = phone
            response_data['college_name'] = college_name
            response_data['branch'] = branch
            # updating the current logged in user values
            user_data = UserProfile.objects.get(emailID = request.user.email)
            if(user_data.emailID == request.user.email):
                UserProfile.objects.filter(emailID = request.user.email).update(
                    user_img = user_img,
                    name = name,
                    emailID = emailID,
                    phone = phone,
                    college_name = college_name,
                    branch = branch
                )
            return render(request, 'edit_profile.html')
    except UserProfile.DoesNotExist:
        name = UserProfile.objects.all()
        response_data = {}
        # creating new user
        if request.POST.get('action') == 'post' and request.FILES:
            # user profile image start
            user_img = request.FILES['user_img']
            # user profile image end
            name = request.user.username
            emailID = request.user.email
            phone = request.POST.get('phone')
            college_name = request.POST.get('college_name')
            branch = request.POST.get('branch')

            response_data['user_img'] = user_img
            response_data['name'] = name
            response_data['emailID'] = emailID
            response_data['phone'] = phone
            response_data['college_name'] = college_name
            response_data['branch'] = branch
            try:
                # checking if the user exist
                user_data = UserProfile.objects.get(emailID = request.user.email)
            except UserProfile.DoesNotExist:
                # if the user doesn't exist create the user
                UserProfile.objects.create(
                    user_img = user_img,
                    name = name,
                    emailID = emailID,
                    phone = phone,
                    college_name = college_name,
                    branch = branch
                )
            return render(request, 'edit_profile.html')
    else:
        # if the profile is already created fetch the values
        context = {
            'user_img' : user_data.user_img.url,
            'name' : user_data.name,
            'emailID' : user_data.emailID,
            'phone' : user_data.phone,
            'college_name' : user_data.college_name,
            'branch' : user_data.branch
            }
        return render(request, 'edit_profile.html', {'context' : context})
    return render(request, 'edit_profile.html')

I am able to fetch the UserProfile image which I have uploaded through django admin. The issue is while submitting the image it is not getting reflected in the database.

  • After changing it to media

settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT =  os.path.join(BASE_DIR, 'media') 
  • urls.py
from django.contrib import admin
from django.urls import path, include
# For user profile
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('colos.urls')),
    path('accounts/', include('allauth.urls')),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
  • models.py
# User profile
class UserProfile (models.Model):
    # user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
    user_img = models.ImageField(null=True, blank=True, upload_to='images/')
    name = models.CharField(max_length=100)
    emailID = models.CharField(max_length=100)
    phone = models.CharField(max_length=15)
    college_name = models.CharField(max_length=200)
    branch = models.CharField(max_length=100)
  • My form in html have added enctype
<form class="form-horizontal" role="form" method="POST" id="post-form" enctype="multipart/form-data">
  • Form code edit_profile.html
<form class="form-horizontal" role="form" method="POST" id="post-form" enctype="multipart/form-data">
                      {% csrf_token %}
                      <div class="form-group">
                        <div class="col-md-3">
                          <div class="text-center">
                            <h6>Upload a different photo...</h6>
                            <input type="file" class="form-control" name="user_img">
                          </div>
                        </div>
                        <label class="col-lg-3 control-label">Full name:</label>
                        <div class="col-sm-9 text-secondary">
                            {{user.username}}
                          </div>
                      </div>
                      <div class="form-group">
                        <label class="col-lg-3 control-label">Email:</label>
                        <div class="col-sm-9 text-secondary">
                            {{user.email}}
                          </div>
                      </div>
                      <div class="form-group">
                        <label class="col-lg-3 control-label">Phone:</label>
                        <div class="col-lg-8">
                          <input class="form-control" type="text" name="phone" value={{context.phone}}>
                        </div>
                      </div>
                      <div class="form-group">
                        <label class="col-md-3 control-label">College Name:</label>
                        <div class="col-md-8">
                          <input class="form-control" type="text" name="college_name" value={{context.college_name}}>
                        </div>
                      </div>
                      <div class="form-group">
                        <label class="col-md-3 control-label">Branch:</label>
                        <div class="col-md-8">
                          <input class="form-control" type="text" name="branch" value={{context.branch}}>
                        </div>
                      </div>
                      <button type="submit" class="btn btn-primary">Submit</button>
                    </form>
                    <script>
                      $(document).on('submit', '#post-form',function(e){
                          console.log("Phone="+$('input[name="phone"]').val());
                          console.log("College Name="+$('input[name="college_name"]').val());
                          console.log("Branch="+$('input[name="branch"]').val());
                          e.preventDefault();
                          // getting the value entered
                          phone = $('input[name="phone"]').val();
                          college_name = $('input[name="college_name"]').val();
                          branch = $('input[name="branch"]').val();
                          user_img = $('input[name="user_img"]').val();
                          console.log(phone);
                          console.log(college_name);
                          console.log(branch);
                          var name = "123" ;
                          var emailID = "abc@gmail.com";
                          $.ajax({
                              type:'POST',
                              url:'{% url "edit_profile" %}',
                              data:{
                                  user_img : user_img,
                                  name: name,
                                  emailID: emailID,
                                  phone: phone,
                                  college_name : college_name,
                                  branch : branch,
                                  csrfmiddlewaretoken: '{{ csrf_token }}',
                                  // csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
                                  action: 'post'
                              },
                              error : function(xhr,errmsg,err) {
                              $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
                                  " <a href='#' class='close'>&times;</a></div>"); // add the error to the dom
                              console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
                          }
                          });
                      });
                  </script>

Solution

  • The QuerySet.update() method doesn't call save() on the model, and so the usual mechanism that places the image into storage is not executed.

    Rather than using update(), if you set the attributes on the model instance and then call save(), the image should get saved to the correct place on disk.

    in your model :

    class UserProfile (models.Model):
        user_img = models.ImageField(null=True, blank=True)
    

    and in your view :

    def edit_profile(request):
        try:
            # checking if the user exist in UserProfile through the logged in email id
            user_data = UserProfile.objects.get(emailID = request.user.email)
            if request.method == "POST" and request.FILES:
                name = UserProfile.objects.all()
                response_data = {}
                # user profile image start
                user_img = request.FILES['user_img']
                # user profile image end
                name = request.user.username
                emailID = request.user.email
                phone = request.POST.get('phone')
                college_name = request.POST.get('college_name')
                branch = request.POST.get('branch')
    
                response_data['user_img'] = user_img
                response_data['name'] = name
                response_data['emailID'] = emailID
                response_data['phone'] = phone
                response_data['college_name'] = college_name
                response_data['branch'] = branch
                # updating the current logged in user values
                user_data = UserProfile.objects.get(emailID = request.user.email)
                if(user_data.emailID == request.user.email):
                    user=UserProfile.objects.get(emailID = request.user.email)
                    user.user_img = user_img,
                    user.name = name,
                    user.emailID = emailID,
                    user.phone = phone,
                    user.college_name = college_name,
                    user.branch = branch
                    user.save()
                    
                return render(request, 'edit_profile.html')
        except UserProfile.DoesNotExist:
            name = UserProfile.objects.all()
            response_data = {}
            # creating new user
            if request.POST.get('action') == 'post' and request.FILES:
                # user profile image start
                user_img = request.FILES['user_img']
                # user profile image end
                name = request.user.username
                emailID = request.user.email
                phone = request.POST.get('phone')
                college_name = request.POST.get('college_name')
                branch = request.POST.get('branch')
    
                response_data['user_img'] = user_img
                response_data['name'] = name
                response_data['emailID'] = emailID
                response_data['phone'] = phone
                response_data['college_name'] = college_name
                response_data['branch'] = branch
                try:
                    # checking if the user exist
                    user_data = UserProfile.objects.get(emailID = request.user.email)
                except UserProfile.DoesNotExist:
                    # if the user doesn't exist create the user
                    UserProfile.objects.create(
                        user_img = user_img,
                        name = name,
                        emailID = emailID,
                        phone = phone,
                        college_name = college_name,
                        branch = branch
                    )
                return render(request, 'edit_profile.html')
        else:
            # if the profile is already created fetch the values
            context = {
                'user_img' : user_data.user_img.url,
                'name' : user_data.name,
                'emailID' : user_data.emailID,
                'phone' : user_data.phone,
                'college_name' : user_data.college_name,
                'branch' : user_data.branch
                }
            return render(request, 'edit_profile.html', {'context' : context})
        return render(request, 'edit_profile.html')
    

    As mentioned in commente try with request.method == "POST"