twitter-bootstrap AttributeError: 'str' 对象没有属性 'fields' 在 GAE 上使用 Django non rel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25615753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 21:27:00  来源:igfitidea点击:

AttributeError: 'str' object has no attribute 'fields' Using Django non rel on GAE

pythondjangotwitter-bootstrapgoogle-app-enginedjango-nonrel

提问by user3117112

I'm doing an app with Django non rel on Google App Engine, and im using Bootstrap...to use Bootstrap on Django Forms i installed django_forms_bootstrap (https://github.com/pinax/django-forms-bootstrap)

我正在 Google App Engine 上使用 Django non rel 做一个应用程序,我正在使用 Bootstrap...要在 Django Forms 上使用 Bootstrap 我安装了 django_forms_bootstrap ( https://github.com/pinax/django-forms-bootstrap)

The thing is...when i deploy on GAE and trying to create a new user (registration) i get the Server Error (500), but the new user is created...the log of GAE show this:

问题是……当我在 GAE 上部署并尝试创建新用户(注册)时,我收到服务器错误 (500),但已创建新用户……GAE 的日志显示:

> Exception in request: Traceback (most recent call last):   File
> "/base/data/home/apps/s~softsystemanager/1.378394621720949564/django/core/handlers/base.py",
> line 113, in get_response
>     response = callback(request, *callback_args, **callback_kwargs)   File
> "/base/data/home/apps/s~softsystemanager/1.378394621720949564/myapp/modulos/presentacion/views.py",
> line 32, in signup_view
>     return render_to_response('presentacion/login.html', context_instance=RequestContext(request))   File
> "/base/data/home/apps/s~softsystemanager/1.378394621720949564/django/shortcuts/__init__.py",
> line 29, in render_to_response
>     return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)   File "/base/data/home/apps/s~softsystemanager/1.378394621720949564/django/template/loader.py",
> line 177, in render_to_string
>     return t.render(context_instance)   File "/base/data/home/apps/s~softsystemanager/1.378394621720949564/django/template/base.py",
> line 140, in render
>     return self._render(context)   File "/base/data/home/apps/s~softsystemanager/1.378394621720949564/django/template/base.py",
> line 134, in _render
>     return self.nodelist.render(context)   File "/base/data/home/apps/s~softsystemanager/1.378394621720949564/django/template/base.py",
> line 830, in render
>     bit = self.render_node(node, context)   File "/base/data/home/apps/s~softsystemanager/1.378394621720949564/django/template/base.py",
> line 844, in render_node
>     return node.render(context)   File "/base/data/home/apps/s~softsystemanager/1.378394621720949564/django/template/loader_tags.py",
> line 124, in render
>     return compiled_parent._render(context)   File "/base/data/home/apps/s~softsystemanager/1.378394621720949564/django/template/base.py",
> line 134, in _render
>     return self.nodelist.render(context)   File "/base/data/home/apps/s~softsystemanager/1.378394621720949564/django/template/base.py",
> line 830, in render
>     bit = self.render_node(node, context)   File "/base/data/home/apps/s~softsystemanager/1.378394621720949564/django/template/base.py",
> line 844, in render_node
>     return node.render(context)   File "/base/data/home/apps/s~softsystemanager/1.378394621720949564/django/template/loader_tags.py",
> line 63, in render
>     result = block.nodelist.render(context)   File "/base/data/home/apps/s~softsystemanager/1.378394621720949564/django/template/base.py",
> line 830, in render
>     bit = self.render_node(node, context)   File "/base/data/home/apps/s~softsystemanager/1.378394621720949564/django/template/base.py",
> line 844, in render_node
>     return node.render(context)   File "/base/data/home/apps/s~softsystemanager/1.378394621720949564/django/template/base.py",
> line 881, in render
>     output = self.filter_expression.resolve(context)   File "/base/data/home/apps/s~softsystemanager/1.378394621720949564/django/template/base.py",
> line 606, in resolve
>     new_obj = func(obj, *arg_vals)   File "/base/data/home/apps/s~softsystemanager/1.378394621720949564/django_forms_bootstrap/templatetags/bootstrap_tags.py",
> line 20, in as_bootstrap
>     form = _preprocess_fields(form)   File "/base/data/home/apps/s~softsystemanager/1.378394621720949564/django_forms_bootstrap/templatetags/bootstrap_tags.py",
> **line 10, in _preprocess_fields
>     for field in form.fields: AttributeError: 'str' object has no attribute 'fields'**

Then i go to the file bootstrap_tags.py and i see no error

然后我转到文件 bootstrap_tags.py,我看不到任何错误

> def _preprocess_fields(form):
>     for field in form.fields:
>         name = form.fields[field].widget.__class__.__name__.lower()
>         if not name.startswith("radio") and not name.startswith("checkbox"):
>             form.fields[field].widget.attrs["class"] = " form-control"
>     return form
> 
> 
> @register.filter def as_bootstrap(form):
>     template = get_template("bootstrap/form.html")
>     form = _preprocess_fields(form)
> 
>     c = Context({
>         "form": form,
>     })
>     return template.render(c)

In the HTML file of my app i got this

在我的应用程序的 HTML 文件中,我得到了这个

<div class="col-md-4 ">
            <form action="." method="POST">
                {%csrf_token%}
                {{ form|as_bootstrap}}
                <button type="submit" class="btn btn-default">Sign UP</button>
            </form>     
        </div>
    </div>

and i don't know if this is useful but here is the form

我不知道这是否有用,但这是表格

class RegisterForm(forms.Form):
    username = forms.CharField(label="Nombre de Usuario",widget=forms.TextInput())
    name = forms.CharField(label="Nombre",widget=forms.TextInput())
    last_name = forms.CharField(label="Apellido",widget=forms.TextInput())
    email = forms.EmailField(label="Correo Electronico", widget=forms.TextInput())
    password_one = forms.CharField(label="Password", widget=forms.PasswordInput(render_value=False))
    password_two = forms.CharField(label="Confirmar Password", widget=forms.PasswordInput(render_value=False))

In fact, the error is with this particular form, because i have another one, the login form, and it works perfectly and im using the same procedure to use the django_forms_bootstrap

事实上,错误出在这个特定的表单上,因为我有另一个表单,即登录表单,它运行良好,我使用相同的程序来使用 django_forms_bootstrap

The source code of my singup_view is:

我的 singup_view 的源代码是:

def signup_view(request):
    form = RegisterForm()
    if request.method == "POST":
        form = RegisterForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            name = form.cleaned_data['name']
            last_name = form.cleaned_data['last_name']
            email = form.cleaned_data['email']
            password_one = form.cleaned_data['password_one']
            password_two = form.cleaned_data['password_two']
            newUser = User.objects.create_user(username=username, first_name=name, last_name=last_name, email=email, password=password_one)
            newUser.save()
            return render_to_response('presentacion/login.html', context_instance=RequestContext(request))
        else:
            ctx = {'form':form}
            return render_to_response('presentacion/sign_up.html',ctx, context_instance=RequestContext(request))
    ctx = {'form':form}
    return render_to_response('presentacion/sign_up.html',ctx, context_instance=RequestContext(request))

Please Help!!!

请帮忙!!!

采纳答案by Burhan Khalid

In your login.htmltemplate, you have {{ form|as_bootstrap }}, but in your code for signing up, you are rendering the template for login, but you are not passing in the form value:

在您的login.html模板中,您有{{ form|as_bootstrap }},但在您的注册代码中,您正在呈现用于登录的模板,但您没有传入表单值:

return render_to_response('presentacion/login.html',
                          context_instance=RequestContext(request))

There is no context here.

这里没有上下文。

You need to fix this by redirecting the user to the login view, instead of rendering the login templatefrom your sign up view.

您需要通过将用户重定向到登录视图来解决此问题,而不是从您的注册视图呈现登录模板

In addition, you should use the rendershortcutwhich will automatically send RequestContext.

此外,你应该使用的render快捷方式,它会自动发送RequestContext

Your are also not checking for duplicate users.

您也没有检查重复的用户。

To fix these issues in your code:

要解决代码中的这些问题:

from django.shortcuts import render, redirect

def signup_view(request):
    form = RegisterForm(request.POST or None)
    ctx = {'form': form}
    if request.method == "POST":
        if form.is_valid():
            username = form.cleaned_data['username']
            name = form.cleaned_data['name']
            last_name = form.cleaned_data['last_name']
            email = form.cleaned_data['email']
            password_one = form.cleaned_data['password_one']
            password_two = form.cleaned_data['password_two']
            if not User.objects.filter(email=email).exists():
                 newUser = User.objects.create_user(username=username,
                                                    first_name=name,
                                                    last_name=last_name,
                                                    email=email,
                                                    password=password_one)
                 newUser.save()
            else:
                 # Do something, because a user
                 # with this email already exists
                 pass
            return redirect('login')

    return render(request, 'presentacion/sign_up.html', ctx)

回答by Programming Mentor

If you ended up here like me with a similar error, in Django 2.2.4, using as_table|crispydoesn't seem to work at all. The solution was to remove as_table:

如果你像我一样在这里遇到类似的错误,在 Django 2.2.4 中, usingas_table|crispy似乎根本不起作用。解决方案是删除as_table

Before

<div class="col-md-4 ">
   <form action="." method="POST">
         {%csrf_token%}
         {{ form.as_table|as_bootstrap}}
         <button type="submit" class="btn btn-default">Sign UP</button>
    </form>     
</div>

After

<div class="col-md-4 ">
   <form action="." method="POST">
         {%csrf_token%}
         {{ form|as_bootstrap}}
         <button type="submit" class="btn btn-default">Sign UP</button>
    </form>     
</div>

This may not answer the OP's question, but if you ended up here like me, hope this helps you.

这可能无法回答 OP 的问题,但如果您像我一样来到这里,希望这对您有所帮助。