我正在构建一个文件上传页面,其中文件将以其名称中的不同前缀保存(get_file_path函数使用instance.mname),但将通过相同的上传模型/表单。我希望在mname ='prefix'中的表单视图中声明前缀。如何将此值从视图传递到表单?
谢谢!
models.py
class Upload(models.Model):
mname = # need it to be passed
document = models.FileField(upload_to=get_file_path, validators=[validate_file_extension])
upload_date=models.DateTimeField(auto_now_add =True)
forms.py
class UploadForm(forms.ModelForm):
class Meta:
model = Upload
fields = ('document',)
views.py
def uploadFile(request):
if request.method == "POST":
file = UploadForm(request.POST, request.FILES, mname='....')
if file.is_valid():
file.save()
答案 0 :(得分:0)
您可以将参数添加到表单的__init__
:
UploadForm(forms.Form):
def __init__(self, path, *args, **kwargs):
super(UploadForm, self).__init__(*args, **kwargs)
self.fields['document'] = forms.FileField(upload_to=path, validators=[validate_file_extension])
使用此参数初始化表单:
file = UploadForm(request.POST, request.FILES, path='...')