如何更改Django表单字段的“名称" HTML属性? [英] How do I change the 'name' HTML attribute of a Django Form field?

查看:74
本文介绍了如何更改Django表单字段的“名称" HTML属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Django 3.0表单

I have a Django 3.0 form

# forms.py
class SignupForm(UserCreationForm):
    email = forms.EmailField()

这呈现为HTML元素

<input type="text" name="email" required id="id_email">

是否可以更改名称"属性?

Is there a way to change the 'name' attribute?

小工具文档建议这些都可能起作用:

The widgets documentation suggests that either of these might work:

# forms.py
class SignupForm(UserCreationForm):
    email = forms.EmailField(
        widget = forms.TextInput(
            attrs = {'name': 'email_address'}
        )
    )

# forms.py
class SignupForm(UserCreationForm):
    email = forms.EmailField()

    email.widget.attrs.update({'name': 'email_address'})

,但都使用两个 name 属性进行渲染;第一个未被替换:

but both render with two name attributes; the first one isn't replaced:

<input type="text" name="email" name="email_address" required id="id_email">

是否有一种简单的方法来更改 name 属性?

Is there a straightforward method of changing the name attribute?

我已经找到了几篇相关的先前文章,但是问题和答案往往比较古老(Django 1.0时代),而且比该过程更令人费解.我希望更新的版本有一个更简单的解决方案.

I've found a couple of related previous posts, but the questions and answers tend to be old (Django 1.0-era) and more convoluted than this process ought to be. I'm hoping that newer versions have a simpler solution.

推荐答案

您可以在SignupForm中覆盖add_prefix方法以获取所需的输出

You can override the add_prefix method in your SignupForm to get the desired output

像这样更新您的表单

class SignupForm(UserCreationForm):
    custom_names = {'email': 'email_address'}

    def add_prefix(self, field_name):
        field_name = self.custom_names.get(field_name, field_name)
        return super(SignupForm, self).add_prefix(field_name)
        
    email = models.CharField(max_length=100)

对add_prefix方法有一点了解选中此内容

to get a little insight of add_prefix method check this out

这篇关于如何更改Django表单字段的“名称" HTML属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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