首页 > 解决方案 > Django ImageField 为空

问题描述

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

Github 回购:https ://github.com/VijaySGill/matching-app

网址.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)

模型.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)

视图.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,
                 ...
      });

表格.py

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

标签: pythondjango

解决方案


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

如果 image.is_valid()

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


推荐阅读