如何仅在与特定用户有关的django中上传图像文件

时间:2019-07-10 05:56:37

标签: python django django-models django-forms django-file-upload

我正在尝试在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对象保存该文件。

1 个答案:

答案 0 :(得分:1)

您可以这样做:

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)