如何仅在与特定用户相关的django中上传图像文件
How to upload image file in django related to a perticular user only
我正在尝试在 Django 中上传文件,以便上传的文件链接到外键。即如果我上传一个文件然后在数据库中它应该反映它与哪个数据库主题相关
这是我的 views.py 文件:
def pod_upload (request, pk):
lr_object = get_object_or_404(LR, id=pk)
if request.method == 'POST':
form = UploadPODform(request.POST, request.FILES)
form.lr_connected = lr_object
form.save()
if form.is_valid():
form.lr_connected = lr_object
form.save()
return redirect('home')
else:
form = UploadPODform()
form.lr_connected = lr_object
return render(request,
'classroom/suppliers/model_form_upload.html', {'form': form})
这是我的 forms.py 文件:
class UploadPODform(forms.ModelForm):
class Meta:
model = Uploaded_pod
fields = ('document',)
def __init__ (self, *args, **kwargs):
super(UploadPODform, self).__init__(*args, **kwargs) #
self.fields['lr_connected'].required = False
这是我的 models.py 文件:
class Uploaded_pod(models.Model):
document = models.FileField(upload_to='pods/')
lr_connected = models.ForeignKey(LR, on_delete=models.CASCADE,
related_name='lr_pod')
我希望如果某些用户上传了一个文件,那么它必须相对于 LR 对象进行保存。
你可以这样做:
def image_path(instance, filename):
return '/'.join(['uploads', instance.lr_connected.pk, filename])
class Uploaded_pod(models.Model):
document = models.FileField(upload_to=image_path)
我正在尝试在 Django 中上传文件,以便上传的文件链接到外键。即如果我上传一个文件然后在数据库中它应该反映它与哪个数据库主题相关
这是我的 views.py 文件:
def pod_upload (request, pk):
lr_object = get_object_or_404(LR, id=pk)
if request.method == 'POST':
form = UploadPODform(request.POST, request.FILES)
form.lr_connected = lr_object
form.save()
if form.is_valid():
form.lr_connected = lr_object
form.save()
return redirect('home')
else:
form = UploadPODform()
form.lr_connected = lr_object
return render(request,
'classroom/suppliers/model_form_upload.html', {'form': form})
这是我的 forms.py 文件:
class UploadPODform(forms.ModelForm):
class Meta:
model = Uploaded_pod
fields = ('document',)
def __init__ (self, *args, **kwargs):
super(UploadPODform, self).__init__(*args, **kwargs) #
self.fields['lr_connected'].required = False
这是我的 models.py 文件:
class Uploaded_pod(models.Model):
document = models.FileField(upload_to='pods/')
lr_connected = models.ForeignKey(LR, on_delete=models.CASCADE,
related_name='lr_pod')
我希望如果某些用户上传了一个文件,那么它必须相对于 LR 对象进行保存。
你可以这样做:
def image_path(instance, filename):
return '/'.join(['uploads', instance.lr_connected.pk, filename])
class Uploaded_pod(models.Model):
document = models.FileField(upload_to=image_path)