【发布时间】: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',)
【问题讨论】: