python - 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',)
解决方案
我会评论,但我不能。发布数据的外观如何,图像实际上是否在其中?您可能想从 ImageField 中删除 blank=True 和 null=True 以进行测试。Django 应该抱怨图像不存在或其他什么。
如果 image.is_valid()
可能返回 false,因此不保存图像
推荐阅读
- mysql - 左连接返回多行而不是一行
- .htaccess - 添加过期标头 - gtmetrix
- angular - 如何将 MatButton 添加到 Angular 库中(Angular 9)
- dji-sdk - 使用 DJI OSDK 时代码不执行我的主要功能
- octobercms - 十月 CMS 属于ToMany/hasMany 与自我的关系
- javascript - 从另一个数组中获取所有相同元素的最快方法
- sql - 从两个表的两列中提取值(Sqlite)
- html - 如果相邻 div 中存在特定类,如何将样式应用于 div
- laravel - 将路径 URL 插入值数组中
- decode - 如何处理类型也许一段时间从/到 Json 去或编码