来自空模型的Django List得到TypeError:unhashable类型:' list'

时间:2016-12-08 11:05:47

标签: django-templates

抱歉我的英语不好,我工作了几天而且我被阻止了,我清理了我的开发/调试数据库,之后我的代码就再也没用了。< / p>

我正在努力了解原因以及如何解决,但没有任何线索。要求任何方法去解决这种情况并帮助我。

我知道我做错了什么,因为只做了:     

    ./manage.py --fork contractos zero
    clean all migrations data on contractos/migrations (except init.py)
    ./manage.py --fake
    ./manage.py makemigrations
    ./manage.py migrate
    ./manage.py runserver
    

<code>
my list.py
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import Http404
from django.shortcuts import render

# Create your views here.
from contractos.models import Contracto


def list(request):
    if not request.user.is_staff and not request.user.is_superuser:
        raise Http404

    contractos_list = Contracto.objects.all() #.order_by("empresa")
    paginator = Paginator(contractos_list, 10)  # Show 25 contacts per page

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

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

    context = {
        "object_list" : contractos,
        "title": "Lista de Contractos",
        "page_request_var": page_request_var,
    }
    return render(request, "contractos/list.html", context)


**my list.html**
{% extends "base.html" %}

{% block content %}
    <div class="col-sm-9 col-sm-offset-1">
        <h1>Contractos {{ title }}</h1>
        <div class="row">
            {% for obj in object_list %}
                <div class="col-sm-6 col-md-4">
                    <div class="thumbnail">
                        <div class="caption">
                            <h3>
                                <a href='{{ obj.get_absolute_url }}'>{{ obj.empresa }} </a><br />
                                {% if obj.logo %}
                                    <img src="{{ obj.logo.url }}" class="img-responsive"/>
                                {% endif %}
                                <small>criado  {{ obj.timestamp|timesince }}</small><br />
                                <small>alterado em {{ obj.updated|timesince }}</small><br />
                            </h3>
                            {{ obj.nfic }} <br/>
                            {{ obj.descricao|linebreaks|truncatechars:60 }}
                            <p>...</p>
                            <p><a href="{{ obj.get_absolute_url }}" class="btn btn-primary" role="button">Detalhes</a>
                                <!--a href="#" class="btn btn-default" role="button">Button</a--></p>
                        </div>
                    </div>
                </div>

                {% cycle "" "<div class='col-sm-12'><hr/></div></div><div class='row'>" %}
            {% endfor %}
        </div>

        <div class="pagination">
            <span class="step-links">
                {% if object_list.has_previous %}
                    <a href="?{{ page_request_var }}=1">Primeira</a>
                    <a href="?{{ page_request_var }}={{ object_list.previous_page_number }}">Anterior</a>
                {% endif %}

                <span class="current">
                    {% if object_list.number %}
                        Pagina {{ object_list.number }} de {{ object_list.paginator.num_pages }}.
                    {% endif %}
                </span>

                {% if object_list.has_next %}
                    <a href="?{{ page_request_var }}={{ object_list.next_page_number }}">Seguinte</a>
                    <a href="?{{ page_request_var }}={{ object_list.paginator.num_pages }}">Ultima</a>
                {% endif %}
            </span>
        </div>
    </div>
{% endblock content %}

**my models.py**

from __future__ import unicode_literals
import uuid

from django.db import models
from django.core.urlresolvers import reverse

STATUS_CHOICES = [
    ('a', 'Activo'),
    ('s', 'Suspenso'),
    ('c', 'Cancelado'),
    ('t', 'Terminado'),
]

def upload_location(instance, filename):
    return "contractos/%s/%s" % (instance.nfic, filename)

# Create your models here.
class Contracto(models.Model):
    slug = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    nfic = models.CharField(max_length=15, default='PT000000000', unique=True)
    empresa = models.CharField(max_length=128, unique=True)
    descricao = models.TextField()
    status = models.CharField(max_length=1, choices=STATUS_CHOICES, default='a')
    logo = models.ImageField(upload_to=upload_location,
                null=True,
                blank=True,
                width_field="width_field",
                height_field="height_field"
                )
    height_field = models.IntegerField(default=0)
    width_field = models.IntegerField(default=0)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

    def __str__(self):
        return self.empresa

    def get_absolute_url(self):

        return reverse("contractos:details", kwargs={"uuid": self.slug})


    class Meta:
        ordering = ["empresa"]
        db_table = ["Contractos"]

and the error I got when try rendering list.py are:
**Environment:**

Request Method: GET
Request URL: http://127.0.0.1:8000/contractos/

Django Version: 1.10.4
Python Version: 3.5.1
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'contractos']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']


Traceback:

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/core/paginator.py" in validate_number
  34.             number = int(number)

**During handling of the above exception (int() argument must be a string, a bytes-like object or a number, not 'NoneType'), another exception occurred:**

File "/home/gwo/Projects/paas/src/contractos/views/list.py" in list
  20.         contractos = paginator.page(page)

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/core/paginator.py" in page
  50.         number = self.validate_number(number)

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/core/paginator.py" in validate_number
  36.             raise PageNotAnInteger('That page number is not an integer')

**During handling of the above exception (That page number is not an integer), another exception occurred:**

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/core/paginator.py" in count
  72.             return self.object_list.count()

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/query.py" in count
  369.         return self.query.get_count(using=self.db)

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/query.py" in get_count
  476.         number = obj.get_aggregation(using, ['__count'])['__count']

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/query.py" in get_aggregation
  457.         result = compiler.execute_sql(SINGLE)

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in execute_sql
  824.             sql, params = self.as_sql()

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in as_sql
  369.             extra_select, order_by, group_by = self.pre_sql_setup()

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in pre_sql_setup
  46.         self.setup_query()

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in setup_query
  36.             self.query.get_initial_alias()

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/query.py" in get_initial_alias
  879.             alias = self.join(BaseTable(self.get_meta().db_table, None))

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/query.py" in join
  921.         alias, _ = self.table_alias(join.table_name, create=True)

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/query.py" in table_alias
  689.         alias_list = self.table_map.get(table_name)

**During handling of the above exception (unhashable type: 'list'), another exception occurred:**

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/gwo/Projects/paas/src/contractos/views/list.py" in list
  23.             contractos = paginator.page(1)

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/core/paginator.py" in page
  50.         number = self.validate_number(number)

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/core/paginator.py" in validate_number
  39.         if number > self.num_pages:

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/utils/functional.py" in __get__
  35.         res = instance.__dict__[self.name] = self.func(instance)

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/core/paginator.py" in num_pages
  84.         if self.count == 0 and not self.allow_empty_first_page:

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/utils/functional.py" in __get__
  35.         res = instance.__dict__[self.name] = self.func(instance)

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/core/paginator.py" in count
  77.             return len(self.object_list)

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/query.py" in __len__
  238.         self._fetch_all()

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/query.py" in _fetch_all
  1087.             self._result_cache = list(self.iterator())

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/query.py" in __iter__
  54.         results = compiler.execute_sql()

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in execute_sql
  824.             sql, params = self.as_sql()

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in as_sql
  369.             extra_select, order_by, group_by = self.pre_sql_setup()

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in pre_sql_setup
  46.         self.setup_query()

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in setup_query
  36.             self.query.get_initial_alias()

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/query.py" in get_initial_alias
  879.             alias = self.join(BaseTable(self.get_meta().db_table, None))

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/query.py" in join
  921.         alias, _ = self.table_alias(join.table_name, create=True)

File "/home/gwo/Projects/paas/lib/python3.5/site-packages/django/db/models/sql/query.py" in table_alias
  689.         alias_list = self.table_map.get(table_name)

**Exception Type: TypeError at /contractos/
Exception Value: unhashable type: 'list'**
</code>
</pre>

所以我只清理我的数据从数据库重新填充然后再次使用测试信息向我们的客户展示项目,你可以想象我必须取消!

1 个答案:

答案 0 :(得分:0)

你不能拥有一个名为list的函数,因为它是一个python关键字。将其更改为其他内容,它将起作用。另外,您应该避免命名文件list等。