【问题标题】:How can i auto-fill a form field based on the title of an attached document?如何根据附加文档的标题自动填写表单域?
【发布时间】:2018-08-10 19:16:47
【问题描述】:

这是我的表格:

models.py:

class Document(models.Model):
    Document_name = models.CharField(max_length=255, default='Document_Name')
    Date = models.DateField()
    Client = models.ForeignKey(ClientDetail, on_delete=models.CASCADE)
    File = models.FileField()
    Filename = models.CharField(max_length=255)

    def __str__(self):
        return self.Document_name

上传.html:

<form method="post" enctype="multipart/form-data" style="margin-left: 16px">
    {% csrf_token %}
    <table>
        {{ form.as_table }}
    </table>
    <button type="submit" class="btn btn-default">Submit</button>
</form>

forms.py:

class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = '__all__'

我想要发生的是当我选择要附加的文档时,例如test1.pptx,我希望文件名字段自动填充该名称(test1.pptx)

【问题讨论】:

    标签: python html django forms


    【解决方案1】:

    在字段中添加 ID

    class Document(models.Model):
        Document_name = models.CharField(max_length=255, default='Document_Name',attrs={'id': 'file-name'})
        Date = models.DateField()
        Client = models.ForeignKey(ClientDetail, on_delete=models.CASCADE)
        File = models.FileField(attrs={'id': 'file-input'})
        Filename = models.CharField(max_length=255)
    
        def __str__(self):
            return self.Document_name
    

    然后在模板中

    <form method="post" enctype="multipart/form-data" style="margin-left: 16px">
        {% csrf_token %}
        <table>
            {{ form.as_table }}
        </table>
        <button type="submit" class="btn btn-default">Submit</button>
    </form>
    <script>
      $('#file-input').on("change", function(){
    
           $("#document-name").val($(this).val());
     });
    
    
    </script>
    

    这将只解析名称,一切都会像魅力一样工作

    【讨论】:

    • 我收到此错误:TypeError: __init__() got an unexpected keyword argument 'attrs' 我必须使用小部件吗?
    • 好的,但目前在我运行它时,每个字段都分配了 ID。我的数据库在 postgresql 中。我还需要在models.py中分配ID吗? id_Filename id_File
    • 哦,如果您已经分配了 ID,只需将 javascript 中的值替换为字段值,然后不要更改您的表单
    • 试过了,但还是没有成功,该字段没有被填充
    • 在答案中检查更新的 js,我很确定是一些 js 问题...你导入了 Jquery 吗?在你的 html 中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 2013-02-17
    • 2017-11-07
    相关资源
    最近更新 更多