Django ImageField为空

时间:2018-12-11 20:12:12

标签: python django

我正在尝试创建一个使用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)

register.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',)

2 个答案:

答案 0 :(得分:0)

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

  

如果image.is_valid()

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

答案 1 :(得分:0)

我建议使用以下方法:

stdout

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) 的路径中。

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