【问题标题】:Image is not getting saved in the database django图像未保存在数据库 django 中
【发布时间】:2021-06-08 02:38:54
【问题描述】:

我正在尝试将图像上传到数据库。在发布数据时,我没有收到任何错误。

图像输入

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

带有图像的模型

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')

我能够获取我通过django admin 上传的UserProfile 图像。问题是在提交图像时它没有反映在数据库中。

  • 改成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)
  • 我在html 中的表格已添加enctype
<form class="form-horizontal" role="form" method="POST" id="post-form" enctype="multipart/form-data">
  • 表格代码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>

【问题讨论】:

  • 你的&lt;form&gt;标签中有enctype="multipart/form-data"吗?
  • @Selcuk 不,我没有。
  • 请注意,此类图像应该被调用并视为媒体文件,而不是静态。您的 ImageField 配置为将它们保存到 static 文件夹中,这并不正确。
  • @IvanStarostin 我对媒体文件进行了更改。它正在发布,但 django 数据库中没有更改。我已经用我已经完成的步骤更新了问题。
  • ImageField 将文件存储在upload_to 选项中提到的文件夹内的文件系统中。我不明白您所说的“数据库没有变化”是什么意思

标签: python django django-media


【解决方案1】:

QuerySet.update() 方法不会在模型上调用 save(),因此不会执行将图像放入存储的常用机制。

而不是使用update(),如果您在模型实例上设置属性然后调用save(),图像应该会保存到磁盘上的正确位置。

在你的模型中:

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

在你看来:

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')

正如评论中提到的,尝试使用request.method == "POST"

【讨论】:

  • 还是没有解决问题
  • 不,我不明白这到底是什么问题。
  • 像我一样更新模型并制作 migrate nd makemigration 你的模型然后在最新的迁移中检查你的迁移文件夹检查是否发现 user_img 文件夹已创建
  • 好吧,我做到了.. user_img 文件夹,即media\image 创建的文件夹。我通过django admin panel 插入了一个虚拟图像。问题仅在于我尝试从前端上传未存储在媒体文件夹中的照片时。
  • 因为现在可以从管理面板更新图像,所以问题出在您的表单中,您可以共享表单的所有代码
猜你喜欢
  • 2013-10-22
  • 2020-03-07
  • 1970-01-01
  • 2021-03-08
  • 1970-01-01
  • 2021-08-25
  • 2011-02-02
  • 1970-01-01
相关资源
最近更新 更多