【问题标题】:Django ImageField is emptyDjango ImageField 为空
【发布时间】:2018-12-11 20:12:11
【问题描述】:

我正在尝试创建一个使用 ajax 来创建新用户的表单。除了 ImageField 之外,所有其他字段都有效。提交时我没有收到错误,但图像仍然无法保存。

Github 仓库:https://github.com/VijaySGill/matching-app

urls.py

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


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

models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    gender = models.CharField(max_length=6, blank=False)
    dateOfBirth = models.DateField(null=True, blank=False)
    bio = models.TextField(max_length=500, blank=True)
    profileImage = models.ImageField(upload_to="profileimage", blank=True, null=True)
    hobby = models.ManyToManyField(Hobby, blank=False)

views.py

@csrf_exempt
def registerUser(request):
         ...
        image = ImageUploadForm(request.POST, request.FILES, instance=newUser)
        if image.is_valid():
            userprofile = image.save(commit=False)
            userprofile.user = request.user
            userprofile.save()
        ...
        return JsonResponse(data, safe=False)

注册.html

$('form').on('submit',function(e){
                e.preventDefault();
                ...
                var fd = new FormData($("#profileImage").get(0));
                fd.append("username", $("#username").val());
                fd.append("email", $("#email").val());
                fd.append("password", $("#password").val());
                fd.append("firstName", $("#firstName").val());
                fd.append("lastName", $("#lastName").val());
                fd.append("gender", gender);
                fd.append("dateOfBirth", dob);
                fd.append("hobbies", JSON.stringify(selectedHobbies));

                if($("#password").val() == $("#confirmPassword").val()){
                $.ajax({
                  type:'POST',
                  url: '/matchingapp/registerUser/',
                        processData: false,
                 contentType: false,
                 data: fd,
                 ...
      });

forms.py

class ImageUploadForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ('profileImage',)

【问题讨论】:

    标签: python django


    【解决方案1】:

    我建议使用以下方法:

    class UserProfile(models.Model):
        user = models.OneToOneField(User, on_delete=models.CASCADE)
        gender = models.CharField(max_length=6, blank=False)
        dateOfBirth = models.DateField(null=True, blank=False)
        bio = models.TextField(max_length=500, blank=True)
        profileImage = models.ImageField(upload_to="UploadTo('user_photo')", blank=True, null=True)
        hobby = models.ManyToManyField(Hobby, blank=False)
    

    其中UploadTo 是一个类,用于将照片保存在媒体文件夹中名为user_photo 的目录下。

    from django.utils.deconstruct import deconstructible
    from uuid import uuid4
    
    @deconstructible
    class UploadTo(object):
    
        def __init__(self, path):
            self.sub_path = path
    
        def __call__(self, instance, filename):
            ext = filename.split('.')[-1]
            # get filename
            if instance.pk:
                filename = '{}.{}'.format(instance.pk, ext)
            else:
                # set filename as random string
                filename = '{}.{}'.format(uuid4().hex, ext)
            # return the whole path to the file
            return os.path.join(self.sub_path, filename)
    

    此类将正确设置要使用的路径,以便可以找到您的照片,因为问题出在您传递给 upload_to 的路径中。

    免责声明:上面的代码不是我的,但对我来说效果很好。

    【讨论】:

      【解决方案2】:

      我会发表评论,但我不能。发布数据的外观如何,图像实际上是否在其中? 您可能想从 ImageField 中删除 blank=True 和 null=True 以进行测试。 Django 应该抱怨图像不存在或其他什么。

      如果 image.is_valid()

      可能返回 false,因此不保存图像

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-21
        • 2012-06-05
        • 2022-06-20
        • 2018-07-26
        • 2013-06-07
        • 2018-05-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多