我正在尝试允许用户上传图片。首次创建用户时,会为他们提供唯一的ID /主键。当用户上传图像时,我想将该图像保存在文件夹中,具体取决于用户的唯一ID。例如,如果用户唯一ID为1,我想将其保存在
中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})
调用uploadImageView视图的URL是/ uploadImage /。当我转到该URL并使用uploadImageForm上传图像时,它会出错:
IntegrityError at /uploadImage/
null value in column "user_id" violates not-null constraint
DETAIL: Failing row contains (1, null, None/uploadedPhotos/imageName.png).
并且追溯返回
form.save()
在我的uploadImageView中排队。我做错了什么导致这个错误?
答案 0 :(得分:2)
您的UserImages
模型需要user
,但您的表单UploadImageForm
仅询问photo
。你需要设置user
,尝试这样的事情:
def uploadImageView(request):
if request.method == 'POST':
form = UploadImageForm(request.POST, request.FILES)
if form.is_valid():
# file is saved
instance = form.save(commit=False)
instance.user = request.user
instance.save()
return redirect('/')
else:
form = UploadImageForm()
return render(request, 'uploadImagePage.html', {'uploadImageForm': form})
答案 1 :(得分:1)
obj = form.save(commit=False)
obj.user = request.user
obj.save()
答案 2 :(得分:1)
您必须从request.user中提取用户并将其添加到表单数据中。