Django表单指示输入类型 [英] Django form to indicate input type

查看:56
本文介绍了Django表单指示输入类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我担心还会遇到另一个基本问题。我浏览了各种Django文档页面,也搜索了该站点。我在这里唯一发现的东西是在2013年,当时建议设置自定义过滤器模板。

Another basic question I'm afraid which I'm struggling with. I've been through the various Django documentation pages and also search this site. The only thing I have found on here was back in 2013 which suggested setting up a custom filter template.

无论如何,我试图生成自己的表单而不是使用Django自己通过{{form}}生成它的方式。

Anyhow, I'm trying to generate my own form instead of using Django's own way of generating it through {{ form }}. This is simply so I can control the way the form is presented.

我已经设计出各种方法来访问所需的信息,例如(在我的for表中)循环);

I've worked out various ways to access the required information such as (within my for item in form loop);


  • item.help_text

  • item.label_tag

  • item.id_for_label

我正在尝试识别商品类型,因此我可以使用正确的输入类型,但是我我正在努力锻炼应使用什么item.xxxx。由于可以通过{{form}}正确显示此信息,因此我假设此信息可以在表单的某个位置使用,只是在努力寻找如何访问它的过程中,才能确定正确的输入类型。我正在手动执行此操作,因此我可以使用正确的Bootstrap样式来显示输入字段。

I'm trying to identify the item type so I can use the correct input type, however I'm struggling to workout what item.xxxx should be. Since this is correctly displayed through {{ form }} I am making an assumption that this information is available somewhere in the form, just struggling to find out how to access it so I can identify the correct input type. I'm doing this manually so I can use the correct Bootstrap styles to display the input fields.

我们将为您提供任何帮助(或只是指向正确的方向)。对于这个基本问题,我很陌生,很抱歉,不认识我就可以问这些问题的人。

Any assistance would be appreciated (or just pointing in the right direction). I'm very new to this so apologies for my very basic questions, its difficult without knowing someone I can just go an ask these questions to.

问候

韦恩

不确定是否需要它,但这是一些代码;

Not sure if you need it but here is some code;

Form:

class NewsForm(ModelForm):
    class Meta:
        model = News_Article
        exclude = ('news_datetime_submitted', 'news_yearmonth', )
        labels = {
            'news_title': _('Enter News Title'),
        }
        help_texts = {
            'news_title': _('Enter a title to give a short description of what the news is.'),
        }
        error_messages = {
            'news_title': {
                'max_length': _("News title is too long."),
            },
        }

视图(尚未在POST上使用,这只是Django文档中的内容,POST是我的下一个

View (not worked on the POST bit yet, this is just what's from the Django documentation, POST is my next thing to work out)

def create(request, dataset):
    if dataset not in ['news', 'announcement']:
        return HttpResponseRedirect(reverse('pages'))
    rDict = {}
    if request.method == 'POST':
        if dataset == "news":
            form = NewsForm(request.POST)
        elif dataset == "announcement":
            form = AnnouncementForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/home/')
        else:
            pass
    else:
        announcement = get_announcement()
        if not announcement == None:
            rDict['announcement'] = announcement
        if dataset == "news":
            rDict['form'] = NewsForm()
            rDict['branding'] = {'heading': 'Create News Item', 'breadcrumb': 'Create News', 'dataset': 'create/' + dataset + '/'}
        elif dataset == "announcement":
            rDict['form'] = AnnouncementForm()
            rDict['branding'] = {'heading': 'Create Announcement', 'breadcrumb': 'Create Announcement', 'dataset': 'create/' + dataset + '/'}
        rDict['sitenav'] = clean_url(request.path, ['"', "'"])
        rDict['menu'] = Menu.objects.all().order_by('menu_position')
#        pdb.set_trace()
        return render(request, 'en/public/admin/admin_create.html', rDict)

模板代码

<form action="/siteadmin/{{ branding.dataset }}" method="post">
    {% csrf_token %}
    {% for item in form %}
        <div class="row">
            <div class="col-xs-2 col-md-2">
            </div>
            <div class="col-xs-4 col-md-4">
                <div class="panel-title pull-right">
                    {% if item.help_text %}
                      <img src="/static/images/info.png" height="20" width="20" aria-hidden="true" data-toggle="popover" title="{{ item.help_text }}">&nbsp
                    {% endif %}
                    {{ item.label_tag }}
                </div>
            </div>
            <div class="col-xs-4 col-md-4">
                <div class="input-group">       
                    <input type="{{ item.widget }}" class="form-control" placeholder="" aria-describedby="{{ item.id_for_label }}">
                </div>
            </div>
            <div class="col-xs-2 col-md-2">
                {% if forloop.last %}
                    <input type="submit" value="Submit" />
                {% endif %}
            </div>          
        </div>
    {% endfor %}
</form>


推荐答案

尝试一下:

<input type="{{ item.field.widget.input_type }}" ...

没有链接到文档,而是通过调试器找到的(不是最佳实践,我知道...)

No link to docs, found it by using debugger (not the best practice, I know...)

根据@Smurf的评论,此功能不适用于所有小部件,例如 Select CheckBox ,任何 MultiWidget 等...似乎仅适用于文本输入及其变体(密码,电子邮件...)

As per @Smurf's comment, this won't work for all widgets, like Select, CheckBox, any MultiWidget, etc... Seems to only work for text input and its variants (password, email...)

更好的解决方案是创建自定义窗口小部件并像往常一样在模板中呈现表单字段。您可以在此处设置任何自定义属性,请参见 https:/ /docs.djangoproject.com/zh-CN/1.8/ref/forms/widgets/#customizing-widget-instances

A better solution is to create custom widgets and render your form fields in template as usual. You can set any custom attributes there, see https://docs.djangoproject.com/en/1.8/ref/forms/widgets/#customizing-widget-instances

如果您绝对必须修改模板中的小部件,请使用 django-widget-tweaks

If you absolutely have to modify widgets in the template, then use django-widget-tweaks

此应用程序提供了一个外观漂亮的表单过滤器,用于更改小部件(即其属性)。但是请注意,它是通过与已渲染的HTML进行字符串修改来实现的(考虑到 Widget 实例为 rendered)。

This app provides a nice-looking form filters to alter widgets (i.e. their attributes). But be aware that it does so by way of string mongering with the already-rendered HTML ("rendered" as concernes the Widget instance).

这篇关于Django表单指示输入类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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