I am relatively new with Django.
I have a models.py file with such attributes:
from datetime import *
from django.db import models
def return_date_time():
now = datetime.now()
return now + timedelta(days=10)
class Job(models.Model):
lastDate = models.DateTimeField(default=return_date_time)
createdAt = models.DateTimeField(auto_now_add=True)
I am able to create new database on /admin, but when editing I get This error
AttributeError at /admin/job/job/2/change/
'datetime.date' object has no attribute 'utcoffset'
There was a very similar post here : https://stackoverflow.com/questions/51870088/django-attributeerror-datetime-date-object-has-no-attribute-utcoffset
but I was not able to solve the problem
The Traceback is as below
Environment:
Request Method: GET
Request URL: http://localhost:8000/admin/job/job/2/change/
Django Version: 4.1.7
Python Version: 3.10.9
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'django.contrib.gis',
'django_filters',
'job.apps.JobConfig']
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/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/contrib/admin/templates/admin/includes/fieldset.html, error at line 19
'datetime.date' object has no attribute 'utcoffset'
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"{% if field.field.id_for_label %} id="{{ field.field.id_for_label }}_helptext"{% endif %}>
24 : {{ field.field.help_text|safe }}
25 : </div>
26 : {% endif %}
27 : </div>
28 : {% endfor %}
29 : </div>
Traceback (most recent call last):
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 56, in inner
response = get_response(request)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 220, in _get_response
response = response.render()
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/response.py", line 114, in render
self.content = self.rendered_content
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/response.py", line 92, in rendered_content
return template.render(context, self._request)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/backends/django.py", line 61, in render
return self.template.render(context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 175, in render
return self._render(context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 167, in _render
return self.nodelist.render(context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/loader_tags.py", line 157, in render
return compiled_parent._render(context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 167, in _render
return self.nodelist.render(context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/loader_tags.py", line 157, in render
return compiled_parent._render(context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 167, in _render
return self.nodelist.render(context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/loader_tags.py", line 63, in render
result = block.nodelist.render(context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/loader_tags.py", line 63, in render
result = block.nodelist.render(context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/defaulttags.py", line 238, in render
nodelist.append(node.render_annotated(context))
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/loader_tags.py", line 208, in render
return template.render(context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 177, in render
return self._render(context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 167, in _render
return self.nodelist.render(context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/defaulttags.py", line 238, in render
nodelist.append(node.render_annotated(context))
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/defaulttags.py", line 238, in render
nodelist.append(node.render_annotated(context))
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/defaulttags.py", line 321, in render
return nodelist.render(context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/defaulttags.py", line 321, in render
return nodelist.render(context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 1070, in render
return render_value_in_context(output, context)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/template/base.py", line 1047, in render_value_in_context
value = str(value)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/utils/html.py", line 419, in <lambda>
klass.__str__ = lambda self: mark_safe(klass_str(self))
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/forms/boundfield.py", line 33, in __str__
return self.as_widget() + self.as_hidden(only_initial=True)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/forms/boundfield.py", line 99, in as_widget
return widget.render(
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/forms/widgets.py", line 280, in render
context = self.get_context(name, value, attrs)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/contrib/admin/widgets.py", line 89, in get_context
context = super().get_context(name, value, attrs)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/forms/widgets.py", line 889, in get_context
value = self.decompress(value)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/forms/widgets.py", line 991, in decompress
value = to_current_timezone(value)
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/forms/utils.py", line 241, in to_current_timezone
if settings.USE_TZ and value is not None and timezone.is_aware(value):
File "/Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/utils/timezone.py", line 256, in is_aware
return value.utcoffset() is not None
Exception Type: AttributeError at /admin/job/job/2/change/
Exception Value: 'datetime.date' object has no attribute 'utcoffset'
Would anyone have any knowledge of what the problem is?
When I try to run makemigrations, it is stated that there is no changes to be made.
The lastDate is a DateTimeField in the Job model. Try to use Django's timezone module to return a timezone-aware datetime object, instead of simply returning datetime object of Python through datetime module, so:
from django.utils import timezone
from django.db import models
def return_date_time():
return timezone.now() + timezone.timedelta(days=10)
class Job(models.Model):
lastDate = models.DateTimeField(default=return_date_time)
createdAt = models.DateTimeField(auto_now_add=True)
Related
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.
How can I fix it?
Error message
Reverse for 'add_comment' with keyword arguments '{'pk': ''}' not found. 2 pattern(s) tried: ['shopping_mall/top_cloth/(?P[0-9]+)/comment\Z', 'top_cloth/(?P[0-9]+)/comment\Z']
Error in line 60
<a class="btn btn-success" href="{% url 'add_comment' pk=product.pk %}">add comment</a>
My URLs
urlpatterns = [
path('', views.index, name='index'),
path('top_cloth/', views.top_cloth),
path('top_cloth/<int:pk>/', views.cloth_detail, name='top_cloth_pk'),
path('top_cloth/<int:pk>/comment', views.add_comment, name='add_comment'),
path('top_cloth/<int:pk>/remove/', views.comment_remove, name='comment_remove'),
path('top_cloth/<int:pk>/modify/', views.comment_modify, name='comment_modify'),
]
My views
def cloth_detail(request, pk):
post = ProductList.objects.get(pk=pk)
product = Comment.objects.order_by()
return render(
request,
'shopping_mall/cloth_detail.html',
{
'post': post, 'product': product
}
)
def add_comment(request, pk):
product = get_object_or_404(ProductList, pk=pk)
if request.method == "POST":
form = CommentFrom(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.author = request.user
comment.product = product
comment.save()
return redirect('index', pk=product.pk)
else:
form = CommentFrom()
return render(request, 'shopping_mall/add_comment.html', {'form':form})
Traceback
Request Method: GET
Request URL: http://127.0.0.1:8000/shopping_mall/top_cloth/1/
Django Version: 4.0.4
Python Version: 3.9.7
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'crispy_forms',
'shopping_mall',
'single_pages',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
'django_summernote']
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 D:\github\kys-shoppingmall\shopping_mall\templates\shopping_mall\cloth_detail.html, error at line 60
Reverse for 'add_comment' with keyword arguments '{'pk': ''}' not found. 2 pattern(s) tried: ['shopping_mall/top_cloth/(?P<pk>[0-9]+)/comment\\Z', 'top_cloth/(?P<pk>[0-9]+)/comment\\Z']
50 : {{ comment.text|linebreaks }}
51 : </p>
52 : </dlv>
53 : {% endif %}
54 :
55 : {% empty %}
56 : <p>Not yet comment</p>
57 : {% endfor %}
58 : {% if user.is_authenticated %}
59 :
60 : <a class="btn btn-success" href=" {% url 'add_comment' pk=product.pk %} "> Add comment</a>
61 : {% else %}
62 : please login
63 : {% endif %}
64 : </section>
65 : {% endblock %}
Traceback (most recent call last):
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\github\kys-shoppingmall\shopping_mall\views.py", line 29, in cloth_detail
return render(
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\shortcuts.py", line 24, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\template\backends\django.py", line 62, in render
return self.template.render(context)
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\template\base.py", line 175, in render
return self._render(context)
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\template\base.py", line 167, in _render
return self.nodelist.render(context)
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\template\base.py", line 1000, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\template\base.py", line 1000, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\template\base.py", line 958, in render_annotated
return self.render(context)
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\template\loader_tags.py", line 157, in render
return compiled_parent._render(context)
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\template\base.py", line 167, in _render
return self.nodelist.render(context)
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\template\base.py", line 1000, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\template\base.py", line 1000, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\template\base.py", line 958, in render_annotated
return self.render(context)
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\template\loader_tags.py", line 63, in render
result = block.nodelist.render(context)
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\template\base.py", line 1000, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\template\base.py", line 1000, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\template\base.py", line 958, in render_annotated
return self.render(context)
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\template\defaulttags.py", line 322, in render
return nodelist.render(context)
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\template\base.py", line 1000, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\template\base.py", line 1000, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\template\base.py", line 958, in render_annotated
return self.render(context)
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\template\defaulttags.py", line 472, in render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\urls\base.py", line 88, in reverse
return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
File "D:\github\kys-shoppingmall\venv\lib\site-packages\django\urls\resolvers.py", line 802, in _reverse_with_prefix
raise NoReverseMatch(msg)
Exception Type: NoReverseMatch at /shopping_mall/top_cloth/1/
Exception Value: Reverse for 'add_comment' with keyword arguments '{'pk': ''}' not found. 2 pattern(s) tried: ['shopping_mall/top_cloth/(?P<pk>[0-9]+)/comment\\Z', 'top_cloth/(?P<pk>[0-9]+)/comment\\Z']
I have been searching on the Internet for a week for a solution to this question, but I can't fix it.
Your product.pk is the empty string, therefore the regex top_cloth/<int:pk>/comment doesn't match (int means [0-9]+ therefore needs at least one character).
Therefore there is no url found (hence the error).
Now, why your product.pk is empty ? I see you try to render cloth_detail.html, and in the view you wrote :
product = Comment.objects.order_by()
Your product is then a list of Comment ? A list has no pk (hence the error).
Let's see your cloth_detail.html because I'm thinking there is some logic error in there too.
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)
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.
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