Django'str'对象没有属性'as_widget' [英] Django 'str' object has no attribute 'as_widget'

查看:65
本文介绍了Django'str'对象没有属性'as_widget'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在django中创建了一个注册表,并且创建了模板标签 add_class 来创建用户,问题是我遇到了以下错误:

I've made a register form in django and i've created a template tag add_class to create users, the problem is i'm getting this error:

'str' object has no attribute 'as_widget'

{{ form.username|add_class:'form-control' }}

register_user.html

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.')

temp最新标签:my_filters.py

template tag: 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添加类。

I've made the template tag so i can add classes from 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)


推荐答案

如果您的表单无效,则重新呈现模板,但您不会dd表单与上下文有关。因此,当模板呈现 {{form.username}} 或其他格式时,它不会找到它-找不到变量时的默认值是使用空字符串。因此,它是将空字符串传递给过滤器,因此会出现错误。

If your form is not valid, you re-render the template but you do not add the form to the context. So, when the template comes to render {{ form.username }} or whatever, it does not find it - and the default when a variable is not found is to use an empty string. So, it is the empty string that gets passed to the filter, hence the error you see.

解决方案是确保始终将表单传递给模板:

The solution is to ensure you always pass the form into the template:

else:
    form = UserForm()
return render(request, 'register_user.html', {'form': form})

这篇关于Django'str'对象没有属性'as_widget'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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