Django - 'function'对象不可迭代 - 模板渲染时出错

时间:2016-07-20 00:27:50

标签: python html django

所以,我一直在尝试创建用户登录。当我在登录表单上单击“提交”时,出现此错误:

Exception Type: TypeError
Exception Value: 'function' object is not iterable 

以下是完整的追溯:http://dpaste.com/3D1B7MG

所以,如果我正确地阅读了Traceback,问题出在all_poss.html的 {%extends“base.html”%} 行。那么这是否意味着问题实际上在base.html内?或者在控制all_posts的视图中?

我的all_posts.html

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <style></style>
<title></title>
</head>
<body>
</body>
</html>

base.html文件

{% load staticfiles %}
{% load crispy_forms_tags %}

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
   <HEAD>
       <link rel="stylesheet"     href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
       <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
       <link rel="stylesheet" href="{% static 'css/base.css' %}">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
      <TITLE>{% block title %}{% endblock %}</TITLE>

</HEAD>

   <BODY>
   {% block content %}
   <div class="navbar-wrapper">
   <div class="post_button" style="width:58px; margin:0 auto;">
   <a href="#" class="btn btn-custom blue">Submit a Post</a>
   </div> <!-- /.post_button-->
   <div class="log_bar">
    <ul>
        {% if user.is_authenticated %}
            <li>Welcome,</li>
            <li><a href="{% url 'profile' %}">{{ user.username }}</a></li>
            <li>|</li>
            <li><a href="{% url 'logout' %}">Log Out</a></li>
        {% else %}
            <li>Please</li>
            <li><a data-toggle="modal" data-target="#modal-login" href="">log in</a></li>
            <li>or</li>
            <li><a data-toggle="modal" data-target="#modal-register" href="">sign up</a></li>
        {% endif %}
    </ul>
    </div><!-- /.log_bar -->
<nav class="navbar navbar-fixed-left navbar-static-top">
  <div class="container-fluid">
    <!-- Collect the nav links, forms, and other content for toggling -->
      <ul class="nav navbar-nav ">
        <li class="active"><a href="/">Home <span class="sr-only">(current)</span></a></li>
        <li><a href="">All</a></li>
        <li><a href="">New</a></li
        <li class="dropdown">
          <a href="" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Top<span class="caret"></span></a>
          <ul class="dropdown-menu">
          <li><a href="">hour</a></li>
          <li><a href="">24 hrs</a></li>
          <li><a href="">week</a></li>
          <li><a href="">month</a></li>
          <li><a href="">year</a></li>
          <li><a href="">beginning of time</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="">Custom Search</a></li>
          </ul>
        </li>
      </ul>
  </div><!-- /.container-fluid -->
</nav>
<div id="side_bar">
     <form class="navbar-form navbar-static-top navbar-right" role="search" id="navBarSearchForm">
                <div class="input-group">
                    <input type="text" class="form-control" placeholder="Search">
                    <span class="input-group-btn">
                        <button type="submit" class="btn btn-default" id="search_btn">
                        <span class="glyphicon glyphicon-search"></span>
                        </button>
                    </span>
            </div>
            </form>
    </div><!-- /.side-bar -->
    <button class="btn-block" id='hideshow' value='hide/show' style="display: block; height: 100%;"></button>

    {% include 'register.html' %}
    {% include 'login.html' %}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">    </script>
    <script  src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"> </script>
    <script type="text/javascript" src="{{ STATIC_URL }} /static/jquery.js"></script>
    <script type="text/javascript" src="{{ STATIC_URL }} /static/jquery.leanModal.js"></script>

{% endblock %}
   </BODY>
</HTML>

views.py

def login(request):
    """
    Log in view
    """
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            user = authenticate(username=request.POST['username'], password=request.POST['password'])
            if user is not None:
                if user.is_active:
                    django_login(request, user)
                    return render(request, 'all_posts.html', {'user': request.user})
    else:
        form = AuthenticationForm()
    return render_to_response('login.html', {
        'authenticationform': form,
    }, context_instance=RequestContext(request))


def all_posts(request):
    post_list = TextPost.objects.all().order_by('-score'))
    paginator = Paginator(post_list, 100) # Show 100 contacts per page
    registrationform = RegistrationForm(request.POST or None)
    authenticationform = AuthenticationForm(request.POST or None)

    page = request.GET.get('page')

    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        posts = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        posts = paginator.page(paginator.num_pages)

    return render(request, 'all_posts.html', {'posts': posts,     'registrationform': registrationform, 'authenticationform': authenticationform, 'user': request.user})

编辑1:login.html login.html和register.html是相同的模式,一个是登录表单,另一个是注册表单。

{% load staticfiles %}
{% load crispy_forms_tags %}

<div class="modal" id="modal-login">
        <div class="modal-dialog">
            <div class="modal-content">
                <form enctype="multipart/form-data" method="post" action="login/">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h3 class="modal-title">Log In</h3>
                    </div>
                    <div class="modal-body">
                        {% csrf_token %}
                        {{ authenticationform|crispy }}
                    </div>
                    <div class="modal-footer">
                        <input type='submit' class="btn btn-primary" value="Log In" />
                    </div>
                </form>
            </div>
        </div>
</div>

编辑2:register.html

{% load staticfiles %}
{% load crispy_forms_tags %}

<div class="modal" id="modal-register">
        <div class="modal-dialog">
            <div class="modal-content">
                <form enctype="multipart/form-data" method="post" action="register/">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h3 class="modal-title">Register</h3>
                    </div>
                    <div class="modal-body">
                        {% csrf_token %}
                        {{ registrationform|crispy }}
                    </div>
                    <div class="modal-footer">
                        <input type='submit' class="btn btn-primary" value="Register" />
                    </div>
                </form>
            </div>
        </div>
</div>

2 个答案:

答案 0 :(得分:1)

好吧,我能够解决它。

问题显然出现在我的base.html中:

<li><a href="{% url 'profile' %}">{{ user.username }}</a></li>

<li><a href="{% url 'logout' %}">Log Out</a></li>

我刚刚将 href =&#34; {%%}&#34; 标记更改为&#34;个人资料/&#34; 和<强>&#34;注销/&#34; 分别

答案 1 :(得分:0)

我在执行Django tutorial时遇到了此错误。

核心问题出在我应用的urls.py的{​​{1}}中,第二个参数在这里:

urlpatterns

应该是:

    path('', views.index, views.IndexView.as_view(), name='index'),

不确定多余的 path('', views.IndexView.as_view(), name='index'), 是如何插入其中的,但这是造成问题的原因。 (关于为什么会出现确切的错误-不会深入探讨)

我相信这比删除views.index调用并按照上述解决方案中的建议对结果进行硬编码更为可取。