【问题标题】:Django modelform widget readonly render text not input fieldDjango modelform 小部件只读渲染文本而不是输入字段
【发布时间】:2016-12-02 14:58:09
【问题描述】:

I have a modelform with readonly fields that render as a HTML input widget with an ugly 'no-entry' mouseover image (firefox) when the text inside the input box is selected - default behaviour for 'models.TextField' fields to我相信渲染为输入。

self.fields['project_path'].widget.attrs['readonly'] = True
self.fields['media_path'].widget.attrs['readonly'] = True
self.fields['responsible'] = SysEventChoiceField(User.objects.all().order_by('first_name'))

我想将混合了只读字段的模型表单呈现为纯文本,而表单中没有输入框。结果在 html 中应该看起来像这样。

<p>D:\This\Path</p>
<p>E:\This\other\path</p>
<input value="Bob Smith" name="user"></input>

【问题讨论】:

    标签: html django modelform


    【解决方案1】:

    我认为您不能替换 Django 表单中的 &lt;input&gt; 标记。相反,您可以获取要显示为 &lt;p&gt; 的字段并单独显示它们。

    在你的views.py中

    # get the fields you want to display as <p>
    my_field = form['my_field'].value()
    
    # remove from the form 
    delete form['my_field']
    
    # pass the parameters to render in your template
    return render_to_response('project.html', {
        'my_field': my_field,
        'form': form
    })
    

    在您的模板 project.html 中

    <p>{{my_field}}</p>
    {{form}}
    

    或者,您也可以执行以下操作:

    {% for field in form %}
        {{ field.value }}
    {% endfor %}
    


    还有as_p() 方法,但这只会将您的输入字段包装在&lt;p&gt; 标记中,我认为您不需要。

    【讨论】:

    • 这也是我正在做的,但感觉就像我错过了一些简单的东西,比如 'self.fields['media_path'].widget.attrs['text_only'] = True
    猜你喜欢
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 2022-10-13
    • 2014-03-19
    相关资源
    最近更新 更多