覆盖Django表单字段的名称attr [英] Override Django form field's name attr

查看:102
本文介绍了覆盖Django表单字段的名称attr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经构建了一个Django表单,提交到另一个域上的页面(我不能控制)。这个想法是,我有一个很好的风格,整齐地生成的表单,适合我自己的网站,并将用户提交到其他地方。

I've built a Django form that submits to a page on another domain (that I don't control). The idea is that I have a nicely styled, neatly generated form that fits neatly into my own site and takes the user elsewhere when it is submitted.

然而,


  • 如果该其他表单更改其任何字段的名称,我需要更改我的表单中的字段名称,然后更改这些名称到处在我的应用程序中,因为名称 attr被耦合到用于该字段的属性名称。

  • 如果远程表单使用愚蠢的名字,那么我的表单对象也必须具有愚蠢的名称的属性,这些属性会污染我的应用程序的代码。

  • 这些名称是否恰好是 Python中的保留字例如中的),那么创建Django表单对象表示是很困难或不可能的。

  • If that other form changes the names of any of its fields, I need to change the names of the fields in my form and then change those names everywhere else in my application - since the name attr is coupled to the name of the property used for the field.
  • If the remote form uses silly names then my form object must also have properties with silly names which pollutes my application's code.
  • Should those names happen to be reserved words in Python (e.g. from), then it is difficult or impossible to create a Django form object representation.

有没有办法在显示字段时,使用不同的字符串来使用name属性?因此,将HTML表单与代表该字段的类分离。

Is there a way to specify a different string to use for the 'name' attribute when the field is displayed? Thus, decoupling the HTML form from the class that represents it.

这将需要两个组件:


  1. 覆盖小部件中的名称值

  2. 使表单读取这个值来自request.POST当它被绑定时

在这种情况下,我只需要第1步,但步骤2与解决问题我更一般地列出了

I only need step 1 in this case, but step 2 is relevant to solve the problems I listed above more generally

推荐答案

这是一个非常可怕的滥用API,但是有一个名为<$调用c $ c> add_prefix ,以确定每个字段的HTML名称应该是什么,考虑到表单的前缀(如果有的话)。您可以覆盖它,以便在字典中查找字段名称,并返回您想要的名称 - 不要忘记保留现有的前缀行为:

This is a pretty horrible abuse of the API, but there is a form method called add_prefix that is called to determine what the HTML name of each field should be, taking into account the form's prefix if any. You could override that so that it looks up the field name in a dictionary somewhere and returns the name you want - not forgetting to preserve the existing prefix behaviour:

FIELD_NAME_MAPPING = {
    'field1': 'html_field1',
    'field2': 'html_field2'
}

class MyForm(forms.ModelForm):
    def add_prefix(self, field_name):
        # look up field name; return original if not found
        field_name = FIELD_NAME_MAPPING.get(field_name, field_name)
        return super(MyForm, self).add_prefix(field_name)

这篇关于覆盖Django表单字段的名称attr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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