我試圖讓用戶上傳圖像。當用戶第一次創建時,他們被賦予一個唯一的ID /主鍵。當用戶上傳圖像時,我想根據用戶唯一ID是什麼將該圖像保存在文件夾中。例如,如果用戶唯一的ID是1,我想將它保存在Django - 將圖像上傳到數據庫引發IntegrityError
1/uploadedPhotos/imageName
這是我的模型:
def get_file_path(instance, filename):
return os.path.join('%s/uploadedPhotos' % instance.user_id, filename)
class UserImages(models.Model):
user = models.ForeignKey(User)
photo = models.ImageField(upload_to=get_file_path)
,這是我的表單:
class UploadImageForm(forms.ModelForm):
class Meta:
model = UserImages
fields = ['photo']
和這是我的看法:
def uploadImageView(request):
if request.method == 'POST':
form = UploadImageForm(request.POST, request.FILES)
if form.is_valid():
# file is saved
form.save()
return redirect('/')
else:
form = UploadImageForm()
return render(request, 'uploadImagePage.html', {'uploadImageForm': form})
調用upl的URL oadImageView視圖是/ uploadImage /。當我去到該網址並上傳使用uploadImageForm的圖像,它提供了一個錯誤說:
IntegrityError at /uploadImage/
null value in column "user_id" violates not-null constraint
DETAIL: Failing row contains (1, null, None/uploadedPhotos/imageName.png).
和回溯導致回我uploadImageView的
form.save()
線。我做錯了什麼導致這個錯誤?