0

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>
Lav Sharma
  • 327
  • 1
  • 5
  • 23
  • 1
    Do you have `enctype="multipart/form-data"` in your `
    ` tag?
    – Selcuk Mar 10 '21 at 07:16
  • @Selcuk No I don't have that. – Lav Sharma Mar 10 '21 at 07:21
  • Note, such images are supposed to be called and treated as **media** files, not **static**. Your `ImageField` is configured to save them into `static` folder which is not really correct. – Ivan Starostin Mar 10 '21 at 07:56
  • @IvanStarostin I am made changes for the media files. It is getting posted but no changes in the django database. I have updated the question with the steps I have done. – Lav Sharma Mar 10 '21 at 08:21
  • ImageField stored files in file system inside folder mentioned in `upload_to` option. I don't understand what you mean by "no changes in database" – Ivan Starostin Mar 10 '21 at 08:31
  • @LavSharma check if you have the reference to your media files from your admin panel. The images don't get stored literally into the database. They get stored locally in the media folder and reference path is stored into the database – SANGEETH SUBRAMONIAM Mar 10 '21 at 08:35
  • @SANGEETHSUBRAMONIAM The folder is not being created neither the image is getting stored in the specified folder and yes i know we just get the url of the image from the database. – Lav Sharma Mar 10 '21 at 08:42
  • What do you mean by `It is getting posted` then? – Ivan Starostin Mar 10 '21 at 08:46
  • yes since you said posted I thouht It got in. why are you uploading to static folder .I dont know if this is an issue, but generally the images upladed should go to the media root. – SANGEETH SUBRAMONIAM Mar 10 '21 at 08:48
  • check this https://stackoverflow.com/a/24193570/8401179 – SANGEETH SUBRAMONIAM Mar 10 '21 at 08:48
  • @IvanStarostin In the network panel you can see that the data is getting poster it shows ```200 OK``` but even a change in the textbox is not getting reflected in the database. – Lav Sharma Mar 10 '21 at 09:03
  • @SANGEETHSUBRAMONIAM the url you provided doesn't solve my issue. And I am uploading it to media root only. – Lav Sharma Mar 10 '21 at 09:03
  • `if request.POST.get('action') == 'post'` -> `if request.method == 'POST'` https://docs.djangoproject.com/en/3.1/ref/request-response/#django.http.HttpRequest.method – Ivan Starostin Mar 10 '21 at 09:14
  • @IvanStarostin Still the same – Lav Sharma Mar 10 '21 at 09:29
  • Continue debugging then. Put `print`s to see what's in variables, do you pass `if` conditions or not, do `.get(` commands find anything or not. You shown a lot of code, some minor flaws were detected, could be there are some more - it's hard to say without debugging, so the question can't be answered directly. – Ivan Starostin Mar 10 '21 at 09:42
  • @LavSharma Well, you should. – Selcuk Mar 11 '21 at 00:00

1 Answers1

2

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"

Belhadjer Samir
  • 1,461
  • 7
  • 15
  • is it still not solving the problem – Belhadjer Samir Mar 10 '21 at 09:30
  • No, I am not getting what is the exact issue in this. – Lav Sharma Mar 10 '21 at 09:35
  • update the model as i did and make migrate nd makemigration your model then check in your migrations folder in the latest migration check if you found that user_img folder is created – Belhadjer Samir Mar 10 '21 at 09:37
  • Well I did that.. The user_img folder i.e. ```media\image``` folder it is created. I have inserted a dummy image through ```django admin panel```. The issue is only while I am trying to upload a photo from front-end which is not getting stored in the media folder. – Lav Sharma Mar 10 '21 at 09:48
  • since image can now updated from admin panel so te problem is in your form can you share all the code of your form – Belhadjer Samir Mar 10 '21 at 09:55
  • I have updated that in my question. I think the issue is in js part of how I am passing the image maybe not really sure. – Lav Sharma Mar 10 '21 at 10:28