简体   繁体   English

将值传递给Django模型属性

[英]Pass value to Django model attribute

I am building a file upload page where files will be saved with a different prefix in their name (get_file_path function uses instance.mname) but will go through the same upload model/form. 我正在构建一个文件上传页面,在该页面中,文件名将以不同的前缀保存(get_file_path函数使用instance.mname),但会通过相同的上传模型/表单。 I want the prefix to be declared in the views in form in mname='prefix'. 我希望前缀在视图中以mname ='prefix'的形式声明。 How can I pass this value from views to form? 如何从视图传递此值到表单?

Thank you! 谢谢!

models.py 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 views.py

def uploadFile(request):
    if request.method == "POST":

        file = UploadForm(request.POST, request.FILES, mname='....')
        if file.is_valid():
           file.save()

You could add a parameter to the __init__ of the form: 您可以在表单的__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])

And initializing the form with this parameter: 并使用此参数初始化表单:

file = UploadForm(request.POST, request.FILES, path='...')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM