python - Django 属性错误 : 'InterestsForm' object has no attribute '_errors'

标签 python django django-1.10

我正在尝试使用 Django 表单允许 Django 用户输入他们最喜欢的三个兴趣。该错误发生在模板呈现期间,它显示为 {{form.as_ul}}

代码如下:

reg_interests.html

{% block content %}

<br><br>
<h1>Choose the 3 things that interest you most!</h1>

<form method="post" action="/reg_interests/">
    {% csrf_token %}
    {{form.as_ul}}
    <br>
    <p class="submit"><input  class="btn btn-default" type="submit" name="commit" value="Continue"></p>
</form>

{% endblock %}

views.py

def reg_interests_view(request):
    if request.POST:
        form = InterestsForm(request.POST, request=request)
        if form.is_valid():
            form.save(request)
            return redirect('/reg_video/')

    args = {}
    args['form'] = InterestsForm(request=request)

    return render(request, 'login/reg_interests.html', args)

表单.py

class InterestsForm(RequestModelForm):
    interest1 = forms.ChoiceField(choices=[(1, "Option 1"), (2, "Option 2")])
    interest2 = forms.ChoiceField(choices=[(1, "Option 1"), (2, "Option 2")])
    interest3 = forms.ChoiceField(choices=[(1, "Option 1"), (2, "Option 2")])

    class Meta:
        model = Interest
        fields = ('interest1', 'interest2', 'interest3')

    def __init__(self, request):
        self.user = request.user

    def save(self, commit=True):
        interest = super(InterestsForm, self).save(commit=False)
        interest.user = self.user
        interest.interest1 = self.cleaned_data['interest1']
        interest.interest2 = self.cleaned_data['interest2']
        interest.interest3 = self.cleaned_data['interest3']

        if commit:
            interest.save()

        return interest

我认为表单有问题,但我不知道如何或为什么需要定义_errors。 Django 本身不应该处理这个问题吗?如果不是,我该如何定义 _errors

最佳答案

此代码根本无法工作,因为您覆盖了表单的 __init__ 方法,因此 a) 您只接受一个 request 参数 - 而不是任何表单期望的其他内容,例如 datainitial - 并且 b) 您永远不会调用父类(super class) init 方法来初始化表单代码的其余部分所期望的内容。您需要保留签名并调用 super。

def __init__(self, *args, **kwargs):
     request = kwargs.pop('request')
     self.user = request.user
     super(InterestsForm, self).__init__(*args, **kwargs)

关于python - Django 属性错误 : 'InterestsForm' object has no attribute '_errors' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38922969/

相关文章:

python - 将预编译的 Cython 代码分发到 Windows

javascript - DRF 在嵌套序列化器中创建用户

django - django 中的电子邮件模板

django - Django-在模板中打印字典

django - BASE_DIR 返回设置路径而不是项目路径(django 1.10)

javascript - AngularJS 上的 Python + Selenium sendkeys

python - 使用 reportlab 将图像放入 pdf 时提高图像质量

python - 需要在 Django Rest Framework 中使用 AnonymousUser 登录

python - 没有 groupby 的自定义描述或聚合