Django List from empty models got TypeError: unhashable type: 'list' - django-templates

Sorry for my poor English, I'm working around several days and I'm blocked, I clean my develop/debug database and after that my code that just didn't work any more.
I'm working for around to understand the reason and how to solve, but no clue. Ask for any path to go to solve this situation and help me.
I know I'm doing something wrong because only did:
./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>Detalhes
<!--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 %}
Primeira
Anterior
{% 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 %}
Seguinte
Ultima
{% 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>
So I only clean my data from database to restart populate then again with test information to demonstrated the project to our customer, that as you can imagine I had to cancel!

You can't have a function called list because it's a python keyword. Change that to something else and it will work. Also you should avoid naming your file list etc.

Related

Django template "image.url" blank when "QuerySet" contains multiple object

I'm having problem with Django templates not receiving any data in image.url when having more than one object in context QuerySet all other data is working fine. If there is only one object in QuerySet, image.url works fine. I'm storing images on S3 and there is nothing wrong with the images or the bucket permission.
I'm new with Django templates is there anything I'm missing?
Here is the code:
models.py
`
from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
from django.utils.translation import gettext_lazy as _
from site_content.models import PageCategory, Page
from site_content.utils import file_upload_to
class PpcOffersPagesManager(models.Manager):
def get_queryset(self):
return super(PpcOffersPagesManager, self) \
.get_queryset() \
.filter(page_category__category_name="ppc-offer-page")
class PpcOfferPages(Page):
objects = PpcOffersPagesManager()
class Meta:
proxy = True
def __str__(self):
return self.page_name
def save(self, *args, **kwargs):
self.page_category = PageCategory.objects.get(category_name="ppc-offer-page")
self.page_site_type = "ppc"
super(PpcOfferPages, self).save(*args, **kwargs)
class PpcOfferContent(models.Model):
related_page = models.ForeignKey(
Page, verbose_name=_("Page"),
related_name="ppc_offer_content",
on_delete=models.SET_NULL,
null=True
)
order = models.IntegerField(verbose_name=_("Order of offer appearance"), default=0)
image = models.ImageField(
verbose_name=_("Casino banner image"),
upload_to=file_upload_to,
null=True,
blank=True,
help_text="Casino banner image, Size (300x500)"
)
header = models.CharField(
verbose_name=_("Header text"),
max_length=500,
null=False,
blank=False
)
is_active = models.BooleanField(verbose_name=_("Is offer active"), default=True)
class Meta:
verbose_name = _('PPC_Offer Page Content')
verbose_name_plural = _('PPC_Offer Page Content')
def __str__(self):
return self.related_page.page_name
`
views.py
`
from django.views.generic import DetailView
from ppc_site_control.models import PpcOfferContent
class PpcOffersDetailView(DetailView):
model = PpcOfferContent
def get_template_names(self):
page = self.model.objects \
.filter(related_page__slug = self.kwargs['slug']) \
.first().related_page.page_template.template_path
return page
def get_object(self):
return self.model.objects \
.filter(related_page__slug=self.kwargs['slug']) \
.filter(is_active=True) \
.order_by('offer_order')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
`
.html
`
{% extends "slotsselection/base.html" %}
{% load i18n static reviews sstags %}
{% for offer in object %}
<div>
<div >
<img loading="lazy" src="{{offer.offer_image.url}}" alt="image">
</div>
<div>
<p>{{offer.header}}</p>
<p>{{offer.is_active }}</p>
</div>
<div>
{% endfor %}
`
I tried sending data in the context as new key and adding QuerySet object again with .values()(to exclude possibility of problem with "get_object" query) still have the same result. When I remove the images from template, all other data is displayed accordingly, without images.
I also tried with ListView same error
ValueError The 'image' attribute has no file associated with it.
Data in context:
`{'object': <QuerySet [<PpcOfferContent: PPC PageName>,
<PpcOfferContent: PPC PageName>, <PpcOfferContent: PPC PageName>,
<PpcOfferContent: PPC PageName>]>, 'view':
<ppc_site_control.views.PpcOffersDetailView object at 0x7f2d8230f430>}
`
The problem was caused from missing images because they were not required in the model the simplest solution is adding "if" condition in the template:
`{% if offer.offer_image %}
<img loading="lazy" src="{{offer.image.url}}" alt="Casino image">
{% endif %}`
I also manage to find workaround:
views.py
`from slotsselection.components.s3_settings import MEDIA_URL`
then in the context data I added
`def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['media_url'] = MEDIA_URL
return context
`
.html
and in html I removed .url to get the half of the link as string and added media_url
`<img loading="lazy" src="{{media_url}}{{offer.offer_image}}" alt="Casino image">`
not best approach but it works to.

Django - Parameter passed to the template but it can not use in if statement

I try to pass the variable to another page using GET method in django. It is possible for me to do that, but the problem is that the variable that I passed is not available in the if statement. I try to print out the value then it worked fine. Then I try to use it inside if statement then I come to know that it was not working properly. I have no idea regarding that. Can anyone help me? Thank you very much.
This is my views:
def test(request):
Test = Photos.objects.all()
ID = request.GET['id']
Context = {
'ID' : ID,
'test' : Test,
'testing' : 3,
}
return render(request, 'test.html', Context)
def tests(request):
tests = Photos.objects.all()
Context = {
'tests' : tests,
}
return render(request, 'tests.html', Context)
This is my urls.py:
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'flashapp.views.home'),
url(r'^play$', 'flashapp.views.play'),
url(r'^test$', 'flashapp.views.test'),
url(r'^tests$', 'flashapp.views.tests'),]
In tests.html I have buttons for passing id to test.html using GET method.
This is tests.html:
</head>
<body>
<h1>Welcome to tests pages.....</h1>
{% for i in tests %}
Click For {{ i.id }}<br>
{% endfor %}
</body>
This is test.html:
<html>
<head>
</head>
<body>
<h1>Welcome to Test Page</h1>
<h1>{{ ID }}</h1>
{% for i in test %}
<p>{{ i.id }}..........{{ testing }}.........{{ ID }}</p>
{% if ID == i.id %}
<p>Test</p>
<p>Working....ID = {{ i.id }}</p>
{% else %}
<p>In else</p>
{% endif %}
{% endfor %}
</body>
this is tests.html
this is test.html
I suppose to see the "Working....." but, it gone to else block. I have no idea. Help me please!!!
Thank you very much.
I edited my original answer based on your comment
You are passing a QuerySet as your Test object instead of an object in the first view, so it doesn't have an id property.
When you do this:
def test(request):
Test = Photos.objects.all()
...
You are getting a collection of all the Photos objects into the Test variable, which is not what you want, you only want one instance of Photos. For that kind of queries, you need to use the .get method, that returns a single instance or an exception in case it doesn't find it.
Test = Photos.objects.get(pk=request.GET['id'])
Your code now should look like this:
def test(request):
ID = request.GET['id']
Test = Photos.objects.get(pk=ID)
Context = {
'ID' : ID,
'test' : Test,
'testing' : 3,
}
return render(request, 'test.html', Context)
Now, for completeness' sake, this would fail in case the ID is not on the database, so we can do something like this:
def test(request):
try:
ID = request.GET['id']
Test = Photos.objects.get(pk=ID)
Context = {
'ID' : ID,
'test' : Test,
'testing' : 3,
}
return render(request, 'test.html', Context)
except Photos.DoesNotExist:
raise Http404("No Photo matches the given query.")
Of course, Django has its own shortcuts for these kind of things, so your code can be written like this:
from django.shortcuts import get_object_or_404
def test(request):
#I strongly suggest you don't use uppercase in variable names
id = request.GET['id']
test = get_object_or_404(pk=id)
context = {
'ID' : id,
'test' : test,
'testing' : 3,
}
return render(request, 'test.html', context)

ValueError at /sup/ invalid literal for int() with base 10: ''

i'm new on stackoverflow and in django
I know this has been asked before, but for my circumstance, I can't seem to figure out why this is being thrown
When I try to delete a user, I am given this error from my console:
ValueError: invalid literal for int() with base 10: ''
Here is my view.py where that code is located:
class Delete_user(DeleteView):
model = AuthUser
template_name = 'delUser.html'
def get_success_url(self):
return reverse('ListUserAdmin')
the templete :
<form action="{% url 'Sup-User' pk=AuthUser.id %}" method="POST">
{% csrf_token %}
<input type="submit" value="Yes, delete." />
No, cancel.
</form>
and this is the url :
url(r'^sup/(?P<pk>.*)', log.views.Delete_user.as_view(),
name='Sup-User',),

NoReverseMatch at /admin/app/model/ - Admin change_list.html

I don't know why I get this error while trying to reach the admin change_list page of the mymodel model:
NoReverseMatch at /admin/myapp/mymodel/
Reverse for 'myapp_mymodel_change' with arguments '(u'',)' and keyword arguments '{}' not found.
Error during template rendering
In template /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/admin/change_list.html, error at line 91
84 <form id="changelist-form" action="" method="post"{% if cl.formset.is_multipart %} enctype="multipart/form-data"{% endif %}>{% csrf_token %}
85 {% if cl.formset %}
86 <div>{{ cl.formset.management_form }}</div>
87 {% endif %}
88
89 {% block result_list %}
90 {% if action_form and actions_on_top and cl.full_result_count %}{% admin_actions %}{% endif %}
91 {% result_list cl %}
92 {% if action_form and actions_on_bottom and cl.full_result_count %}{% admin_actions %}{% endif %}
93 {% endblock %}
94 {% block pagination %}{% pagination cl %}{% endblock %}
95 </form>
The error does not occur on my local runserver(Python 2.7.5, Django 1.5.1), only when deployed on my remote server (Python 2.7.2+, Django 1.5.1). Interestingly enough, only one specific model is affected by this -- I can reach the change_list pages of all the other models without any problems whatsoever. The rest of the admin area works fine as well.
The answers to similar questions regarding the NoReverseMatch error didn't help much because it happens in the admin, not my own code. Does anyone know where to start looking?
EDIT:
I had some customised list_display fields which I now commented out for testing. They seemed to be responsible for the NoReverseMatch error. Now I got another error instead:
AttributeError at /admin/myapp/mymodel/
'NoneType' object has no attribute '_meta'
I then stripped away everything that isn't necessary. This is now my complete admin.py:
from django.contrib import admin
from myproject.myapp.models import *
class MymodelAdmin(admin.ModelAdmin):
list_display = ['email', 'user', 'is_active', 'first_used']
date_hierarchy = 'first_used'
ordering = ['-first_used']
list_filter = ['is_active', 'first_used', 'user']
admin.site.register(Mymodel, MymodelAdmin)
And on my local machine it still works perfectly.
There are some variables which are not getting passed during rendering the template ..
Take your lead by checking the required local variables to be passed as to fulfill the url pattern in url tag ..
I encountered same problem when my foreign key is null while using this script not originally mine on my admin change_list.html.
What it does is to display the column for foreign_key of your model.
from django.forms import MediaDefiningClass
class ModelAdminWithForeignKeyLinksMetaclass(MediaDefiningClass):
def __getattr__(cls, name):
def foreign_key_link(instance, field):
# Please note in Django 1.6
# Model._meta.module_name was renamed to model_name
target = getattr(instance, field)
return u'%s' % (
target._meta.app_label, target._meta.model_name, target.id, unicode(target))
if name[:8] == 'link_to_':
method = partial(foreign_key_link, field=name[8:])
method.__name__ = name[8:]
method.allow_tags = True
setattr(cls, name, method)
return getattr(cls, name)
raise AttributeError
I added a line if target: in filter out those null values.
if target:
return u'%s' % (
target._meta.app_label, target._meta.model_name, target.id, unicode(target))
Script usage:
where carrier,sitename are a foreign key field.
class LatestRsl_v2Admin(admin.ModelAdmin):
__metaclass__ = classmaker(right_metas=(ModelAdminWithForeignKeyLinksMetaclass,))
list_display = ['issued', 'link_to_carrier', ]
search_fields = ['=rslno','=issued','link_to_carrier', 'link_to_sitename']

Django template tag for Model query result

I wonna simple tag, for showing table of any model arrays like:
{% table city_list %}
Do anybody see such things?
You can try django-tables app, which allows you to do the following, given model Book:
# Define
class BookTable(tables.ModelTable):
id = tables.Column(sortable=False, visible=False)
book_name = tables.Column(name='title')
author = tables.Column(data='author__name')
class Meta:
model = Book
# In your views
initial_queryset = Book.objects.all()
books = BookTable(initial_queryset)
return render_to_response('table.html', {'table': books})
# In your template table.html
<table>
<!-- Table header -->
<tr>
{% for column in table.columns %}
<th>{{ column }}</th>
{% endfor %}
</tr>
<!-- Table rows -->
{% for row in table.rows %}
<tr>
{% for value in row %}
<td>{{ value }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
I think the above is much more elegant and self explanatory than just doing
{% table book_list %}
Try generic vieww e.g. http://www.djangobook.com/en/2.0/chapter11/
I've made a fork of django-tables which makes this extremely easy. Here's a simple example:
In models.py:
from django.db import models
class City(models.Model):
name = models.CharField(max_length=200)
state = models.CharField(max_length=200)
country = models.CharField(max_length=200)
In tables.py:
import django_tables as tables
from .models import City
class CityTable(tables.Table):
class Meta:
model = City
In views.py:
from django.shortcuts import render_to_response
from django.template import RequestContext
from .models import City
from .tables import CityTable
def city_list(request):
queryset = City.objects.all()
table = CityTable(queryset)
return render_to_response("city_list.html", {"city_table": table},
context_instance=RequestContext(request))
In city_list.html:
{% load django_tables %}
{% render_table city_table %}