我在django中创建了一个注册表单,我创建了一个模板标记add_class
来创建用户,问题是我收到了这个错误:
'str' object has no attribute 'as_widget'
到
{{ form.username|add_class:'form-control' }}
register_user.html
<form class="form-horizontal" method="POST" action="">
{% csrf_token %}
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<div class="form-group">
<div class="col-md-12">
{{ form.username|add_class:'form-control' }}
</div>
</div>
<div class="form-group">
<div class="col-md-12">
{{ form.email|add_class:'form-control' }}
</div>
</div>
<div class="form-group">
<div class="col-md-12">
{{ form.password|add_class:'form-control' }}
</div>
</div>
<div class="form-group">
<div class="col-md-12">
{{ form.confirm_password|add_class:'form-control' }}
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<button type="submit" class="btn btn-info btn-block">Register</button>
<input type="hidden" name="next" value="{% url 'register_user_success' %}"/>
</div>
</div>
</form>
form.py
class UserForm(ModelForm):
username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Username'}))
password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'}))
email = forms.EmailField(widget=forms.EmailInput(attrs={'placeholder': 'E-mail'}))
confirm_password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password'}))
class Meta:
model = CustomUser
fields = ('username', 'email', 'password', 'confirm_password')
def clean(self):
cleaned_data = super(UserForm, self).clean()
password = cleaned_data.get('password')
confirm_password = cleaned_data.get('confirm_password')
if password != confirm_password:
raise forms.ValidationError('Password did not match.')
模板标签:my_filters.py
from django import template
register = template.Library()
@register.filter(name='add_class')
def add_class(value, arg):
return value.as_widget(attrs={'class': arg})
我已经制作了模板标签,因此我可以从css中添加类。
views.py
def register_user(request):
data = dict()
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.set_password(user.password)
user.save()
return redirect('/register_user/success/')
else:
data['form'] = UserForm()
return render(request, 'register_user.html', data)
答案 0 :(得分:2)
如果表单无效,则重新呈现模板,但不将表单添加到上下文中。因此,当模板来渲染{{ form.username }}
或其他什么时,它找不到它 - 并且当找不到变量时的默认值是使用空字符串。因此,它是传递给过滤器的空字符串,因此是您看到的错误。
解决方案是确保您始终将表单传递到模板中:
else:
form = UserForm()
return render(request, 'register_user.html', {'form': form})