Django:如何访问模板中的表单字段input_type [英] Django: How to access form field input_type in a template

查看:234
本文介绍了Django:如何访问模板中的表单字段input_type的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以这种方式呈现表单:

I am rendering a form this way:

{% for field in form %}
    <div>
        {{ field.errors }}
        <input  name="{{field.name}}" type="{{field.widget.input_type}}" placeholder="{{field.name}}">
    </div>
{% endfor %}

但是, {{ widget.input_type}} 在此处返回空字符串,尽管从shell尝试它会产生 input_type 。那么如何从模板访问字段的输入类型?

However, {{field.widget.input_type}} returns the empty string here, though trying it from the shell it produces the input_type. So how can I access the input type of a field from the template?

我没有使用 {{field}} 因为我需要在每个输入字段中放置一个占位符。

I am not using {{field}} because I need to put a placeholder in each input field.

编辑:

我刚刚使用过 {{field}} 和一个简单的javascript,它们将占位符放置在每个输入元素字段中,与元素名称相同,尽管我仍然想知道如何访问模板中的 widget.input_type

I just used {{field}} and a simple javascript, that place the placeholder in each input element field to be the same as the element name, though I still would like to know how to access widget.input_type from the template.

推荐答案

我是否可以建议和使用另一种方法来获得相同的东西?

Could I perhaps suggest and alternate means to get same thing?

尝试放置

attrs = {'placeholder':'your placeholder text here'}

进入表单字段小部件,如下所示:

into your form field widget like this:

formfield = SomeField(widget = SomeWidget(attrs = {'placeholder':'your placeholder text here'} ))

然后您就可以打印出

{{ field }} 

并在模板中完成。

编辑:响应第一个评论。

In response to first comment.

由于我刚刚开始新项目并在页面顶部下载了具有漂亮圆滑的loginform的html5样板,因此我必须按照我的建议去做。我是那样做的:

Since i just started new project and downloaded html5 boilerplate with nice sleek loginform on top of the page i had to just do exactly what i suggested. I did it like that:

forms.py:

from django.contrib.auth.forms import AuthenticationForm

class MyAuthenticationForm(AuthenticationForm):
    def __init__(self, *args, **kwargs):
        super(MyAuthenticationForm, self).__init__(*args, **kwargs)
        self.fields['username'].widget.attrs['placeholder'] = self.fields['username'].label
        self.fields['password'].widget.attrs['placeholder'] = self.fields['password'].label

现在也许您的问题是您还想使用django.contrib.auth.views.login登录用户,并且该视图使用django默认身份验证形式。没问题!

Now perhaps your problem is that you want to also use django.contrib.auth.views.login for logging user in and that view uses django default authentication form. Not a problem!

打开您的urls.py并发挥这种魔力:

open your urls.py and work this magic:

from yourapp.forms import MyAuthenticationForm
from django.contrib.auth.views import login

urlpatterns = patterns('',
    url(r'^login/$',
        login,
        {'template_name': 'yourapp/login.html', 'authentication_form':MyAuthenticationForm},
        name='auth_login'),
)

工作就像吊饰一样

这篇关于Django:如何访问模板中的表单字段input_type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆