Recursion Error - Maximum Recursion dept exceeded when ForeignKey('self') django - python

I am getting an error in admin console while trying to open a model (employees in my case). This is occurring after adding a field which is a ForeignKey('self'). I guess it is conflicting with str method. If I comment out the method, there is no error, but all the objects in the model are appearing as 'employee object'. Here is what my error looks like https://ibb.co/jHt84Q
Here is my models.py:
from django.db import models
import calendar
from datetime import datetime
from datetime import timedelta
class employees(models.Model):
emp_id=models.PositiveIntegerField()
emp_name = models.CharField(max_length = 100)
emp_lname = models.CharField(max_length = 100)
emp_loc = models.CharField(max_length = 100,null=True)
manager_id=models.ForeignKey('self',null=True,blank=True)
image=models.ImageField(upload_to='profile_image',default='/profile_image/profile-icon.png')
email = models.EmailField(default='app-engine#gmail.com', blank=False)
def __str__(self):
return str(self.emp_id) + '-' + self.emp_name + '-' + self.emp_loc+'-'+str(self.manager_id)
class leave(models.Model):
employee = models.ForeignKey(employees, on_delete=models.CASCADE, default='1')
start_date = models.DateField()
end_date = models.DateField()
status=models.CharField(max_length=1,default='P')
ltype=models.CharField(max_length=2)
message=models.CharField(max_length=500,blank=True)
date_created = models.DateTimeField(auto_now_add=True)
def leave_length(self):
return self.end_date - self.start_date+timedelta(days=1);
def __str__(self):
return str(self.id) + '/' + str(self.employee.emp_name) +'/'+str(self.start_date) +'/'+str(self.end_date) +'/'+str(self.status)+'/'+str(self.date_created)
Here is my traceback:
Environment:
Request Method: GET
Request URL: http://localhost:8000/admin/apply/employees/
Django Version: 1.11.3
Python Version: 3.6.0
Installed Applications:
['apply.apps.ApplyConfig',
'm_manage',
'pending.apps.PendingConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
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']
Template error:
In template C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\contrib\admin\templates\admin\base.html, error at line 75
maximum recursion depth exceeded while calling a Python object 65 : <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message|capfirst }}</li>
66 : {% endfor %}</ul>
67 : {% endif %}
68 : {% endblock messages %}
69 :
70 : <!-- Content -->
71 : <div id="content" class="{% block coltype %}colM{% endblock %}">
72 : {% block pretitle %}{% endblock %}
73 : {% block content_title %}{% if title %}<h1>{{ title }}</h1>{% endif %}{% endblock %}
74 : {% block content %}
75 : {% block object -tools %}{% endblock %}
76 : {{ content }}
77 : {% endblock %}
78 : {% block sidebar %}{% endblock %}
79 : <br class="clear" />
80 : </div>
81 : <!-- END Content -->
82 :
83 : {% block footer %}<div id="footer"></div>{% endblock %}
84 : </div>
85 : <!-- END Container -->
Traceback:
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\db\models\options.py" in get_field
617. return self.fields_map[field_name]
During handling of the above exception ('__str__'), another exception occurred:
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\contrib\admin\utils.py" in lookup_field
283. f = _get_non_gfk_field(opts, name)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\contrib\admin\utils.py" in _get_non_gfk_field
317. field = opts.get_field(name)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\db\models\options.py" in get_field
619. raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name))
During handling of the above exception (employees has no field named '__str__'), another exception occurred:
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\db\models\fields\related_descriptors.py" in __get__
178. rel_obj = getattr(instance, self.cache_name)
During handling of the above exception ('employees' object has no attribute '_manager_id_cache'), another exception occurred:
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\core\handlers\exception.py" in inner
41. response = get_response(request)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\core\handlers\base.py" in _get_response
217. response = self.process_exception_by_middleware(e, request)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\core\handlers\base.py" in _get_response
215. response = response.render()
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\template\response.py" in render
107. self.content = self.rendered_content
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\template\response.py" in rendered_content
84. content = template.render(context, self._request)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\template\backends\django.py" in render
66. return self.template.render(context)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\template\base.py" in render
207. return self._render(context)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\template\base.py" in _render
199. return self.nodelist.render(context)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\template\base.py" in render
990. bit = node.render_annotated(context)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\template\base.py" in render_annotated
957. return self.render(context)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\template\loader_tags.py" in render
177. return compiled_parent._render(context)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\template\base.py" in _render
199. return self.nodelist.render(context)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\template\base.py" in render
990. bit = node.render_annotated(context)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\template\base.py" in render_annotated
957. return self.render(context)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\template\loader_tags.py" in render
177. return compiled_parent._render(context)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\template\base.py" in _render
199. return self.nodelist.render(context)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\template\base.py" in render
990. bit = node.render_annotated(context)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\template\base.py" in render_annotated
957. return self.render(context)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\template\loader_tags.py" in render
72. result = block.nodelist.render(context)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\template\base.py" in render
990. bit = node.render_annotated(context)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\template\base.py" in render_annotated
957. return self.render(context)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\template\loader_tags.py" in render
72. result = block.nodelist.render(context)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\template\base.py" in render
990. bit = node.render_annotated(context)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\template\base.py" in render_annotated
957. return self.render(context)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\template\library.py" in render
225. _dict = self.func(*resolved_args, **resolved_kwargs)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\contrib\admin\templatetags\admin_list.py" in result_list
340. 'results': list(results(cl))}
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\contrib\admin\templatetags\admin_list.py" in results
316. yield ResultList(None, items_for_result(cl, res, None))
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\contrib\admin\templatetags\admin_list.py" in __init__
307. super(ResultList, self).__init__(*items)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\contrib\admin\templatetags\admin_list.py" in items_for_result
218. f, attr, value = lookup_field(field_name, result, cl.model_admin)
File "C:\Users\rhshanka\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.3-py3.6.egg\django\contrib\admin\utils.py" in lookup_field
299. value = attr()
File "C:\Users\rhshanka\LMS\apply\models.py" in __str__
15. return str(self.emp_id) + '-' + self.emp_name + '-' + self.emp_loc+'-'+str(self.manager_id)
Exception Type: RecursionError at /admin/apply/employees/
Exception Value: maximum recursion depth exceeded while calling a Python object

Try it:
def __str__(self):
self_str = '%s-%s-%s' % (self.emp_id, self.emp_name, self.emp_loc)
if self.manager_id and self.manager_id.pk != self.pk:
return '%s-%s' % (self_str, str(self.manager_id))
return self_str
And you need to be sure your logic is correct, for many inherits it will be not readable.

Related

How to limit the number of responses to my for loop to 3 in Django Templates?

In my current Django template I have two models in use, which are defined in my views.py as:
'tasks' : IndividualTask.objects.all(),
'updates' : TaskUpdate.objects.all(),
I have set up signals so that when there is an update to a task, an update is created.
Currently, I iterate through each task, then each of their updates and pull out the relevant updates for each task, as shown below.
{% for task in tasks %}
{% for update in updates %}
{% if task.id == update.task.id %}
{{ update.update }}
{% endif %}
{% endfor %}
{% endfor %}
However, I would like to limit the number of updates I show to three.
I have tried using slice, show below, but this limits all updates to the top 3 of all updates as opposed to the top 3 of each individual task's updates.
{% for task in tasks %}
{% for update in updates|slice:":3" %}
{% if task.id == update.task.id %}
{{ update.update }}
{% endif %}
{% endfor %}
{% endfor %}
Models.py is as below:
class IndividualTask(models.Model):
task = models.CharField(
max_length = 256,
blank=False,
null=True,
)
task_description = models.CharField(
max_length = 256,
blank=False,
null=True,
)
expected_completion = models.DateField(
max_length = 64,
null=True,
)
goal = models.ForeignKey(
IndividualGoal,
on_delete=models.CASCADE,
related_name="goals",
blank=False,
null=True,
)
creator = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name="creator",
blank=False,
null=True,
)
owner = models.ForeignKey(
User,
on_delete=models.CASCADE,
blank=False,
null=True,
)
status_choices = [
("", "Select Current Status"),
("Preparation", "Preparation"),
("Review", "Review"),
("Update", "Update"),
("Finalised", "Finalised"),
]
current_status = models.CharField(
max_length=32,
choices = status_choices,
default = "Select current status",
)
created = models.DateField(
auto_now_add = True,
)
def __str__(self):
return f"{self.task}"
class TaskUpdate(models.Model):
update = models.CharField(
max_length = 5000,
)
task = models.ForeignKey(
IndividualTask,
on_delete=models.CASCADE,
null = True,
)
update_created = models.DateField(
auto_now_add = True,
)
update_time_created = models.TimeField(
auto_now_add = True,
)
author = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name="update_author",
blank=True,
null=True,
)
update_choices = [
("New Task", "New Task"),
("New Commentary", "New Commentary"),
]
update_status = models.CharField(
max_length=32,
choices = update_choices,
null = True,
)
class Meta:
ordering = ["-update_created", "-update_time_created"]
I would be grateful for any advice as to how I can limit the number of updates shown for each task to 3 please?
EDIT:
Full traceback shown below:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/tasks/
Django Version: 4.0.2
Python Version: 3.9.10
Installed Applications:
['tasks.apps.TasksConfig',
'notes',
'accounts',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
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']
Template error:
In template /Users/Tom/Desktop/squeasy/tasks/templates/tasks/tasks.html, error at line 69
'RelatedManager' object is not iterable
59 : Expected Completion Date
60 : </div>
61 : <div class = expected_completion>
62 : {{ task.expected_completion }}
63 : </div>
64 : </div>
65 : </div>
66 : <div class = task_sub_header>
67 : Latest updates:
68 : </div>
69 : {% for update in task.taskupdate_set|slice:":3" %}
70 : {% if task.id == update.task.id %}
71 : <div class = individual_update>
72 : {% if update.update_status == "New Task" %}
73 : {{ update.author }} created this task on {{ update.update_created|date:"l jS F" }} at {{ update.update_time_created|time:"H:i" }}
74 : {% elif update.update_status == "New Commentary" %}
75 : {{ update.author }} updated the commentary for {{ update.task }} on {{ update.update_created|date:"l jS F" }} at {{ update.update_time_created|time:"H:i" }}
76 : {% endif %}
77 : </div>
78 : {% endif %}
79 : {% endfor %}
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/Tom/Desktop/squeasy/tasks/views.py", line 28, in tasks
return render(request, "tasks/tasks.html", context)
File "/usr/local/lib/python3.9/site-packages/django/shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "/usr/local/lib/python3.9/site-packages/django/template/loader.py", line 62, in render_to_string
return template.render(context, request)
File "/usr/local/lib/python3.9/site-packages/django/template/backends/django.py", line 61, in render
return self.template.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 176, in render
return self._render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 168, in _render
return self.nodelist.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 977, in render
return SafeString(''.join([
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 978, in <listcomp>
node.render_annotated(context) for node in self
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 938, in render_annotated
return self.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/loader_tags.py", line 153, in render
return compiled_parent._render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 168, in _render
return self.nodelist.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 977, in render
return SafeString(''.join([
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 978, in <listcomp>
node.render_annotated(context) for node in self
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 938, in render_annotated
return self.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/loader_tags.py", line 65, in render
result = block.nodelist.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 977, in render
return SafeString(''.join([
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 978, in <listcomp>
node.render_annotated(context) for node in self
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 938, in render_annotated
return self.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/defaulttags.py", line 298, in render
return nodelist.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 977, in render
return SafeString(''.join([
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 978, in <listcomp>
node.render_annotated(context) for node in self
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 938, in render_annotated
return self.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/defaulttags.py", line 217, in render
nodelist.append(node.render_annotated(context))
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 938, in render_annotated
return self.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/defaulttags.py", line 217, in render
nodelist.append(node.render_annotated(context))
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 938, in render_annotated
return self.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/defaulttags.py", line 298, in render
return nodelist.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 977, in render
return SafeString(''.join([
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 978, in <listcomp>
node.render_annotated(context) for node in self
File "/usr/local/lib/python3.9/site-packages/django/template/base.py", line 938, in render_annotated
return self.render(context)
File "/usr/local/lib/python3.9/site-packages/django/template/defaulttags.py", line 173, in render
values = list(values)
Exception Type: TypeError at /tasks/
Exception Value: 'RelatedManager' object is not iterable
In the context you can pass the IndividualTasks with the TaskUpdates ordered in descending order with a Prefetch object [Django-doc]:
from django.db.models import Prefetch
context = {
'tasks' : IndividualTask.objects.prefetch_related(
Prefetch('taskupdate_set', TaskUpdate.objects.order_by('-update_created', '-update_time_created'))
)
}
then in the template you enumerate over the taskupdate_set:
{% for task in tasks %}
{% for update in task.taskupdate_set.all|slice:":3" %}
{{ update.update }}
{% endfor %}
{%endfor %}
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Exception Value: __str__ returned non-string (type int) in django model

I want to create a function that returns the list of last points per vehicle that have sent navigation data in the last 48 hours. I create a view it works and it displays name correctly but when I want to add new Vehicle from Django Admin panel it shows an error.
TypeError at /admin/navigation/navigationrecord/add/
str returned non-string (type int)
How can I fixed it? And is there a more afformative and efficient way to list data over the past 48 hours?
models.py
class Vehicle(models.Model):
id = models.IntegerField(primary_key=True)
plate = models.CharField(max_length=30)
def __str__(self):
return str(self.plate)
class NavigationRecord(models.Model):
id = models.IntegerField(primary_key=True)
vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE)
datetime = models.DateField(default=timezone.now)
latitude = models.FloatField()
longitude = models.FloatField()
def __str__(self):
return self.vehicle
views.py
def get_48_hours(request):
time_48 = datetime.now() - timedelta(hours=48)
results = NavigationRecord.objects.filter(datetime__gte=time_48)
context = {
'results': results,
}
return render(request, 'navigation.html', context)
navigation.html
<table class="table table-hover">
<thead>
<tr>
<th>ID</th>
<th>Vehicle</th>
</tr>
</thead>
<tbody>
{% for result in results %}
<tr>
<td>{{result.id}}</td>
<td>{{result.vehicle}}</td>
<td>{{result.datetime}}</td>
</tr>
{% endfor %}
</tbody>
</table>
admin.py
models = [Vehicle, NavigationRecord]
admin.site.register(models)
traceback
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/navigation/navigationrecord/add/
Django Version: 2.2.13
Python Version: 3.7.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'navigation']
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']
Template error:
In template C:\Users\edeni\senior\myenv\lib\site-packages\django\contrib\admin\templates\admin\includes\fieldset.html, error at line 19
__str__ returned non-string (type int)
9 : {% for field in line %}
10 : <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}>
11 : {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %}
12 : {% if field.is_checkbox %}
13 : {{ field.field }}{{ field.label_tag }}
14 : {% else %}
15 : {{ field.label_tag }}
16 : {% if field.is_readonly %}
17 : <div class="readonly">{{ field.contents }}</div>
18 : {% else %}
19 : {{ field.field }}
20 : {% endif %}
21 : {% endif %}
22 : {% if field.field.help_text %}
23 : <div class="help">{{ field.field.help_text|safe }}</div>
24 : {% endif %}
25 : </div>
26 : {% endfor %}
27 : </div>
28 : {% endfor %}
29 : </fieldset>
Traceback:
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\core\handlers\base.py" in _get_response
145. response = self.process_exception_by_middleware(e, request)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\core\handlers\base.py" in _get_response
143. response = response.render()
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\response.py" in render
106. self.content = self.rendered_content
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\response.py" in rendered_content
83. content = template.render(context, self._request)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\backends\django.py" in render
61. return self.template.render(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in render
171. return self._render(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in _render
163. return self.nodelist.render(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in render
937. bit = node.render_annotated(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\loader_tags.py" in render
150. return compiled_parent._render(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in _render
163. return self.nodelist.render(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in render
937. bit = node.render_annotated(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\loader_tags.py" in render
150. return compiled_parent._render(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in _render
163. return self.nodelist.render(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in render
937. bit = node.render_annotated(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\loader_tags.py" in render
62. result = block.nodelist.render(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in render
937. bit = node.render_annotated(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\loader_tags.py" in render
62. result = block.nodelist.render(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in render
937. bit = node.render_annotated(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\defaulttags.py" in render
209. nodelist.append(node.render_annotated(context))
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\loader_tags.py" in render
188. return template.render(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in render
173. return self._render(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in _render
163. return self.nodelist.render(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in render
937. bit = node.render_annotated(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\defaulttags.py" in render
209. nodelist.append(node.render_annotated(context))
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\defaulttags.py" in render
209. nodelist.append(node.render_annotated(context))
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\defaulttags.py" in render
309. return nodelist.render(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in render
937. bit = node.render_annotated(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\defaulttags.py" in render
309. return nodelist.render(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in render
937. bit = node.render_annotated(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in render_annotated
904. return self.render(context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in render
993. return render_value_in_context(output, context)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\template\base.py" in render_value_in_context
972. value = str(value)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\utils\html.py" in <lambda>
388. klass.__str__ = lambda self: mark_safe(klass_str(self))
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\forms\boundfield.py" in __str__
33. return self.as_widget()
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\forms\boundfield.py" in as_widget
93. renderer=self.form.renderer,
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\forms\widgets.py" in render
241. context = self.get_context(name, value, attrs)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\contrib\admin\widgets.py" in get_context
288. 'rendered_widget': self.widget.render(name, value, attrs),
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\forms\widgets.py" in render
241. context = self.get_context(name, value, attrs)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\forms\widgets.py" in get_context
678. context = super().get_context(name, value, attrs)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\forms\widgets.py" in get_context
639. context['widget']['optgroups'] = self.optgroups(name, context['widget']['value'], attrs)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\forms\widgets.py" in optgroups
587. for index, (option_value, option_label) in enumerate(self.choices):
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\forms\models.py" in __iter__
1138. yield self.choice(obj)
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\forms\models.py" in choice
1150. return (self.field.prepare_value(obj), self.field.label_from_instance(obj))
File "C:\Users\edeni\senior\myenv\lib\site-packages\django\forms\models.py" in label_from_instance
1216. return str(obj)
Exception Type: TypeError at /admin/navigation/navigationrecord/add/
Exception Value: __str__ returned non-string (type int)
If you look at the stracktrace, it literally says: __str__ returned non-string (type int).
This is caused by your NavigationRecord' __str__ method which returns self.vehicle which is the foreignkey, thus a integer. Try changing this method to return a str of the self.vehicle instead. That should call __str__ on the Vehicle class.
def __str__(self):
return str(self.vehicle)

How to fix TypeError __str__ returned non-string

My code it still gives the error of __str__ returned non-string (type Contact) despite the fact that i cast the return statement with str()
My model:
class Contact(models.Model):
name = models.CharField("Contact Name", max_length=50)
surname = models.CharField("Contact Surname", max_length=50)
company = models.ForeignKey(Customer, verbose_name='Company',on_delete=models.CASCADE)
department = models.ForeignKey(Department, verbose_name='Department',on_delete=models.CASCADE)
position = models.CharField("Position", max_length=50, null=True, blank=True)
birthday = models.DateField("Birthday", null=True, blank=True)
remarks = models.TextField("Remarks", max_length=500, null=True, blank=True)
skype = models.CharField("Spype", max_length=50, null=True, blank=True)
def clean(self):
for field in self._meta.fields:
if isinstance(field, (models.CharField, models.TextField)) and getattr(self, field.name)!=None:
setattr(self, field.name, getattr(self, field.name).strip())
class Meta:
verbose_name = "Contact"
#####Overide save method to store names and surnames in caps
def save(self, *args, **kwargs):
for attr_name in ['name', 'surname', 'position']:
val = getattr(self, attr_name, False)
if val:
setattr(self, attr_name, val.upper())
super(Contact, self).save(*args, **kwargs)
def __str__(self):
return self.surname + " " + self.name
I also used to write the str function like this:
def __str__(self):
return str(self.surname + " " + self.name)
but still the code returns the same error.
Here is my traceback
Django Version: 2.2.6
Python Version: 3.5.2
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'adminactions',
'django.contrib.admin',
'intranet',
'daterange_filter',
'gunicorn',
'notifications')
Installed Middleware:
('whitenoise.middleware.WhiteNoiseMiddleware',
'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')
Template error:
In template /usr/local/lib/python3.5/dist-packages/django/contrib/admin/templates/admin/edit_inline/tabular.html, error at line 33
__str__ returned non-string (type Contact)
23 : <tbody>
24 : {% for inline_admin_form in inline_admin_formset %}
25 : {% if inline_admin_form.form.non_field_errors %}
26 : <tr><td colspan="{{ inline_admin_form|cell_count }}">{{ inline_admin_form.form.non_field_errors }}</td></tr>
27 : {% endif %}
28 : <tr class="form-row {% cycle "row1" "row2" %} {% if inline_admin_form.original or inline_admin_form.show_url %}has_original{% endif %}{% if forloop.last and inline_admin_formset.has_add_permission %} empty-form{% endif %}"
29 : id="{{ inline_admin_formset.formset.prefix }}-{% if not forloop.last %}{{ forloop.counter0 }}{% else %}empty{% endif %}">
30 : <td class="original">
31 : {% if inline_admin_form.original or inline_admin_form.show_url %}<p>
32 : {% if inline_admin_form.original %}
33 : {{ inline_admin_form.original }}
34 : {% if inline_admin_form.model_admin.show_change_link and inline_admin_form.model_admin.has_registered_model %}{% if inline_admin_formset.has_change_permission %}{% trans "Change" %}{% else %}{% trans "View" %}{% endif %}{% endif %}
35 : {% endif %}
36 : {% if inline_admin_form.show_url %}{% trans "View on site" %}{% endif %}
37 : </p>{% endif %}
38 : {% if inline_admin_form.needs_explicit_pk_field %}{{ inline_admin_form.pk_field.field }}{% endif %}
39 : {% if inline_admin_form.fk_field %}{{ inline_admin_form.fk_field.field }}{% endif %}
40 : {% spaceless %}
41 : {% for fieldset in inline_admin_form %}
42 : {% for line in fieldset %}
43 : {% for field in line %}
Traceback:
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py" in _get_response
145. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py" in _get_response
143. response = response.render()
File "/usr/local/lib/python3.5/dist-packages/django/template/response.py" in render
106. self.content = self.rendered_content
File "/usr/local/lib/python3.5/dist-packages/django/template/response.py" in rendered_content
83. content = template.render(context, self._request)
File "/usr/local/lib/python3.5/dist-packages/django/template/backends/django.py" in render
61. return self.template.render(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render
171. return self._render(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in _render
163. return self.nodelist.render(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render
937. bit = node.render_annotated(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render_annotated
904. return self.render(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/loader_tags.py" in render
150. return compiled_parent._render(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in _render
163. return self.nodelist.render(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render
937. bit = node.render_annotated(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render_annotated
904. return self.render(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/loader_tags.py" in render
150. return compiled_parent._render(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in _render
163. return self.nodelist.render(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render
937. bit = node.render_annotated(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render_annotated
904. return self.render(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/loader_tags.py" in render
62. result = block.nodelist.render(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render
937. bit = node.render_annotated(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render_annotated
904. return self.render(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/loader_tags.py" in render
62. result = block.nodelist.render(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render
937. bit = node.render_annotated(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render_annotated
904. return self.render(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/defaulttags.py" in render
209. nodelist.append(node.render_annotated(context))
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render_annotated
904. return self.render(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/loader_tags.py" in render
188. return template.render(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render
173. return self._render(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in _render
163. return self.nodelist.render(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render
937. bit = node.render_annotated(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render_annotated
904. return self.render(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/defaulttags.py" in render
209. nodelist.append(node.render_annotated(context))
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render_annotated
904. return self.render(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/defaulttags.py" in render
309. return nodelist.render(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render
937. bit = node.render_annotated(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render_annotated
904. return self.render(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/defaulttags.py" in render
309. return nodelist.render(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render
937. bit = node.render_annotated(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render_annotated
904. return self.render(context)
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render
993. return render_value_in_context(output, context)
File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render_value_in_context
972. value = str(value)
Exception Type: TypeError at /private/intranet/contact/742/change/
Exception Value: __str__ returned non-string (type Contact)
my view
#staff_member_required#login is required
def contact_view(request, intranet_contact_id):
contact = Contact.objects.get(id = intranet_contact_id)
emails = Contact_email.objects.filter(contact_name = intranet_contact_id)
phones = Contact_Phone.objects.filter(contact_name = intranet_contact_id)
other_company_contacts = Contact.objects.filter(company = contact.company.id).exclude(pk= intranet_contact_id)
return render(request,'contact/details.html', dict(contact = contact, emails = emails, phones = phones, other_company_contacts = other_company_contacts))
admin.py
class ContactAdmin(ReadPermissionModelAdmin):
list_display = ['show_name', 'company', 'department', 'position', 'show_details','skype']
list_filter = ['company']
search_fields = ('surname', 'name', 'company__customer_name','skype')
inlines = [Contact_PhoneInline, Contact_emailInline]
#alphabet_filter = 'remarks'
#DEFAULT_ALPHABET = u'T'
formfield_overrides = {
models.CharField: {'widget': TextInput(attrs={'size':'25'})},
models.BigIntegerField: {'widget': TextInput(attrs={'size':'25'})},
models.TextField: {'widget': Textarea(attrs={'rows':6, 'cols':40})},
}
fieldsets = (
(None, {
'fields': (('name', 'surname'), ('company', 'department'), ('position', 'birthday'), ('skype'), ('remarks'),)
}),
)
list_per_page = 20
def response_change(self, request, obj, post_url_continue=None):
#This makes the response go to contact full detail page for an edited order
return HttpResponseRedirect(reverse('contacts', args=(obj.id,)))
#return HttpResponseRedirect("../../contacts/%s/" % obj.id)
def response_add(self, request, obj, post_url_continue=None):
#This makes the response go to contact full detail page for a newlly added order to inquiry list
return HttpResponseRedirect(reverse('contacts', args=(obj.id,)))
#return HttpResponseRedirect("../../contacts/%s/" % obj.id)
def show_name(self, obj):
return obj
show_name.short_description = 'Name'
show_name.admin_order_field = 'surname'
def show_details(self, obj):
#sos
#return 'Details' % (obj.id)
return format_html('Details',str(obj.id))
show_details.allow_tags = True
show_details.short_description = 'Details'
admin.site.register(Contact, ContactAdmin)
How can i deal wih that?
Try changing the show_name function to:
def show_name(self, obj):
return obj.__str__()
show_name.short_description = 'Name'
show_name.admin_order_field = 'surname'
A quick test I've done seem to indicate that while it's fine to expect linked object via a foreign key will render their str fine, the instance itself seems to break when I try to either pass the obj back.
The support was very helpful.
Finally i came up with the solution.
The error occured because the str functions of the inline classes related with the Contact model was false.

key error value 0 on modelformset when queryset is empty

i want to create multiple instances of a model using a modelformset.
but when the queryset is empty and the parameter extra is greater than 0 it raises this error:
Environment:
Request Method: GET
Request URL: http://localhost:8000/alta_socies/proces_alta_projecte_autoocupat/adreces/
Django Version: 1.7.7
Python Version: 2.7.9
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.formtools',
'inici',
'alta_socies',
'empreses',
'socies')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Template error:
In template /home/usergci/gestioci/alta_socies/templates/alta_socies/proces_alta_autoocupat.html, error at line 59
0
49 : <div class="row">
50 : <div class="medium-12 columns content">
51 : <div class="row">
52 : <div class="medium-12 columns">
53 : <div class="group">
54 : <h2>{{ projecte.pas }}</h2>
55 : {% block explicacio_pas %}{% endblock %}
56 : </div>
57 : <form method="post" action="">{% csrf_token %}
58 : {{ wizard.management_form }}
59 : {% if wizard.form.forms %}
60 : {{ wizard.form.management_form }}
61 : {% for form in wizard.form.forms %}
62 : {% block step_factory_form %}
63 : {% endblock %}
64 : {% endfor %}
65 : {% else %}
66 : {% block step_single_form %}
67 : {% endblock %}
68 : {% endif %}
69 : <input class="small radius button" type="submit" name="save_only" value="Guardar y salir"/>
Traceback:
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
137. response = response.render()
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/response.py" in render
103. self.content = self.rendered_content
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/response.py" in rendered_content
80. content = template.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in render
148. return self._render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in _render
142. return self.nodelist.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in render
844. bit = self.render_node(node, context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/debug.py" in render_node
80. return node.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/loader_tags.py" in render
126. return compiled_parent._render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in _render
142. return self.nodelist.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in render
844. bit = self.render_node(node, context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/debug.py" in render_node
80. return node.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/loader_tags.py" in render
126. return compiled_parent._render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in _render
142. return self.nodelist.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in render
844. bit = self.render_node(node, context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/debug.py" in render_node
80. return node.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/loader_tags.py" in render
126. return compiled_parent._render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in _render
142. return self.nodelist.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in render
844. bit = self.render_node(node, context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/debug.py" in render_node
80. return node.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/defaulttags.py" in render
402. return strip_spaces_between_tags(self.nodelist.render(context).strip())
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in render
844. bit = self.render_node(node, context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/debug.py" in render_node
80. return node.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/loader_tags.py" in render
65. result = block.nodelist.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in render
844. bit = self.render_node(node, context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/debug.py" in render_node
80. return node.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/loader_tags.py" in render
65. result = block.nodelist.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in render
844. bit = self.render_node(node, context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/debug.py" in render_node
80. return node.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/defaulttags.py" in render
305. match = condition.eval(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/defaulttags.py" in eval
898. return self.value.resolve(context, ignore_failures=True)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in resolve
596. obj = self.var.resolve(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in resolve
734. value = self._resolve_lookup(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in _resolve_lookup
770. current = getattr(current, bit)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/utils/functional.py" in __get__
55. res = instance.__dict__[self.func.__name__] = self.func(instance)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/forms/formsets.py" in forms
141. forms = [self._construct_form(i) for i in xrange(self.total_form_count())]
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/forms/models.py" in _construct_form
591. kwargs['initial'] = self.initial_extra[i - self.initial_form_count()]
Exception Type: KeyError at /alta_socies/proces_alta_projecte_autoocupat/adreces/
Exception Value: 0
the offending lines as far as i debugged are:
AdrecesFormSet = modelformset_factory(AdrecaProjecteAutoocupat,
form=FormulariAdrecaProjecteAutoocupat,
can_delete=True)
any hint?
The wizard form was expecting a list of dicts intead of a dict!!! The problem was somewhere else in the views.py

KeyError at /admin/myapp/userprofile/1/

I upgraded Django from 1.6 to 1.7.
Now I am getting this error in the Admin panel:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/myapp/userprofile/1/
Django Version: 1.7
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
'django.contrib.sites',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
'feincms',
'rest_framework',
'subdomains',
'social.apps.django_app.default')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'subdomains.middleware.SubdomainURLRoutingMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'social.apps.django_app.middleware.SocialAuthExceptionMiddleware',
'myapp.middleware.SocialAuthExceptionMiddleware')
Template error:
In template /home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/contrib/admin/templates/admin/includes/fieldset.html, error at line 17
manager
7 : <div class="form-row{% if line.fields|length_is:'1' and line.errors %} errors{% endif %}{% if not line.has_visible_field %} hidden{% endif %}{% for field in line %}{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% endfor %}">
8 : {% if line.fields|length_is:'1' %}{{ line.errors }}{% endif %}
9 : {% for field in line %}
10 : <div{% if not line.fields|length_is:'1' %} class="field-box{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}>
11 : {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %}
12 : {% if field.is_checkbox %}
13 : {{ field.field }}{{ field.label_tag }}
14 : {% else %}
15 : {{ field.label_tag }}
16 : {% if field.is_readonly %}
17 : <p> {{ field.contents }} </p>
18 : {% else %}
19 : {{ field.field }}
20 : {% endif %}
21 : {% endif %}
22 : {% if field.field.help_text %}
23 : <p class="help">{{ field.field.help_text|safe }}</p>
24 : {% endif %}
25 : </div>
26 : {% endfor %}
27 : </div>
Traceback:
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
137. response = response.render()
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/response.py" in render
103. self.content = self.rendered_content
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/response.py" in rendered_content
80. content = template.render(context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/base.py" in render
148. return self._render(context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/base.py" in _render
142. return self.nodelist.render(context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/base.py" in render
844. bit = self.render_node(node, context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/debug.py" in render_node
80. return node.render(context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/loader_tags.py" in render
126. return compiled_parent._render(context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/base.py" in _render
142. return self.nodelist.render(context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/base.py" in render
844. bit = self.render_node(node, context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/debug.py" in render_node
80. return node.render(context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/loader_tags.py" in render
126. return compiled_parent._render(context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/base.py" in _render
142. return self.nodelist.render(context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/base.py" in render
844. bit = self.render_node(node, context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/debug.py" in render_node
80. return node.render(context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/loader_tags.py" in render
65. result = block.nodelist.render(context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/base.py" in render
844. bit = self.render_node(node, context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/debug.py" in render_node
80. return node.render(context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/loader_tags.py" in render
65. result = block.nodelist.render(context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/base.py" in render
844. bit = self.render_node(node, context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/debug.py" in render_node
80. return node.render(context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/defaulttags.py" in render
201. nodelist.append(node.render(context))
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/loader_tags.py" in render
150. return template.render(context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/base.py" in render
148. return self._render(context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/base.py" in _render
142. return self.nodelist.render(context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/base.py" in render
844. bit = self.render_node(node, context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/debug.py" in render_node
80. return node.render(context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/defaulttags.py" in render
201. nodelist.append(node.render(context))
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/defaulttags.py" in render
201. nodelist.append(node.render(context))
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/defaulttags.py" in render
312. return nodelist.render(context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/base.py" in render
844. bit = self.render_node(node, context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/debug.py" in render_node
80. return node.render(context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/defaulttags.py" in render
312. return nodelist.render(context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/base.py" in render
844. bit = self.render_node(node, context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/debug.py" in render_node
80. return node.render(context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/debug.py" in render
90. output = self.filter_expression.resolve(context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/base.py" in resolve
596. obj = self.var.resolve(context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/base.py" in resolve
734. value = self._resolve_lookup(context)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/template/base.py" in _resolve_lookup
788. current = current()
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/contrib/admin/helpers.py" in contents
183. f, attr, value = lookup_field(field, obj, model_admin)
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/contrib/admin/utils.py" in lookup_field
280. value = attr()
File "/home/ashish/.virtualenvs/myapp_venv/local/lib/python2.7/site-packages/django/db/models/fields/related.py" in __call__
654. manager = getattr(self.model, kwargs.pop('manager'))
Exception Type: KeyError at /admin/myapp/userprofile/1/
Exception Value: u'manager'
What changes am I supposed to make in the code so I can make it work with Django 1.7?
Do I have to make changes in some related fields ?
Edit:
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.core.validators import RegexValidator
# Create your models here.
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
class UserProfile(AbstractUser):
dob=models.DateTimeField(blank=True,null=True)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True,blank=True)
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
phone_number = models.CharField(validators=[phone_regex], blank=True,max_length=16,null=True) # validators should be a list
location=models.CharField(max_length=30,null=True,blank=True)
about=models.CharField(max_length=140,null=True,blank=True)
admin.py
from django.contrib import admin
# Register your models here.
from myapp.models import UserProfile
class user_index_Admin(admin.ModelAdmin):
def get_readonly_fields(self, request, obj=None):
if obj:
return UserProfile._meta.get_all_field_names()
else:
return []
def has_delete_permission(self, request, obj=None):
return False
admin.site.register(UserProfile,user_index_Admin);
The error was in admin class in this line :
return UserProfile._meta.get_all_field_names() . I wanted to make all the fields readonly. I changed the code according to this SO answer and it worked.
admin.py
from django.contrib import admin
# Register your models here.
from myapp.models import UserProfile
class user_index_Admin(admin.ModelAdmin):
def get_readonly_fields(self, request, obj=None):
if obj:
return [f.name for f in self.model._meta.fields]
else:
return []
def has_delete_permission(self, request, obj=None):
return False
admin.site.register(UserProfile,user_index_Admin);

Categories

Resources