gpt4 book ai didi

python - Django 表单不渲染小部件

转载 作者:太空宇宙 更新时间:2023-11-03 15:11:01 25 4
gpt4 key购买 nike

我想向我的字段添加占位符,但由于某种原因,这不起作用。当我查看页面源代码时,占位符属性甚至不存在。

这是我的 forms.py:

class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True, max_length=254)

class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2',)
widgets = {
'username' : forms.TextInput(attrs={'placeholder': 'Username'}),
'email' : forms.TextInput(attrs={'placeholder': 'Email'}),
'password1' : forms.TextInput(attrs={'placeholder': 'Password'}),
'password2' : forms.TextInput(attrs={'placeholder': 'Confirm Password'}),
}

这是我用于 HTML 的模板:

<!DOCTYPE html>

{% extends 'base.html' %}
{% load staticfiles %}

{% block content %}
<section class="container">
<div class="row centre-v">
<div class="card login-card">
<div class="main card-block">
<h1>Sign up</h1>
<div class="login-or">
<hr class="hr-or">
</div>
<form action="." method="post" class="register-form">
{% csrf_token %}
{% for field in form %}
<p>
{{ field }}
{% for error in field.errors %}
<div class="alert alert-danger" role="alert"><strong>{{ error }}</strong></div>
{% endfor %}
</p>
{% endfor %}
<div class="btn-login">
<input class="btn btn-info" type="submit" value="Register">
</div>
</form>
</div>
</div>
</div>
</section>
{% endblock %}

最佳答案

根据docs对于 ModelFormMeta 类仅用于从底层模型生成字段。在 ModelForm 类中显式声明的字段不受 Meta 中设置的属性影响。您在类中声明email,并在继承的UserCreationForm 类中声明password1password2。 (username 是自动生成的,因此您在 Meta 类中设置的小部件属性可能适用于该字段。)要为声明的字段设置属性,您可以使用 self.fields 字典。

class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True, max_length=254)

class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2',)

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs):
self.fields['username'].widget.attrs['placeholder'] = 'Username'
self.fields['email'].widget.attrs['placeholder'] = 'Email'
self.fields['password1'].widget.attrs['placeholder'] = 'Password'
self.fields['password2'].widget.attrs['placeholder'] = 'Confirm Password'

关于python - Django 表单不渲染小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44209150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com