Getting Django Tables2 to work - python

I'm trying to get django_tables2 to work, but I keep getting an error. I already have it installed and it's already in my settings.
models.py
class Schedules(models.Model):
course_name = models.CharField(max_length=128, choices=COURSE_NAME_CHOICES, default='a-plus')
location = models.CharField(max_length=128, choices=LOCATION_CHOICES, default='south_plainfield')
room = models.CharField(max_length=128, choices=ROOM_CHOICES, default='A')
start_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.date.today)
start_time = models.CharField(max_length=128, choices=START_TIME_CHOICES, default='eight-thirty am')
end_time = models.CharField(max_length=128, choices=END_TIME_CHOICES, default='eight-thirty am')
instructor = models.CharField(max_length=128, choices=INSTRUCTOR_CHOICES, default='adewale')
total_hours = models.CharField(max_length=128, choices=TOTAL_HOURS_CHOICES, default='six')
hours_per_class = models.CharField(max_length=128, choices=HOURS_PER_CLASS_CHOICES, default='four_and_half')
frequency = models.CharField(max_length=128)
status = models.CharField(max_length=128, choices=STATUS_CHOICES)
interval = models.CharField(max_length=128, choices=INTERVAL_CHOICES, default='1 day')
initiated_by = models.CharField(max_length=128, null=True)
schedule_id = models.IntegerField(default=0)
def save(self, flag=True, *args, **kwargs):
super(Schedules, self).save()
if flag:
self.schedule_id = self.id + 10000
self.save(flag=False, *args, **kwargs)
tables.py
import django_tables2 as tables
from schedule.models import Schedules
class ScheduleTable(tables.Table):
class Meta:
model = Schedules
views.py
from schedule.models import Schedules
from schedule.tables import ScheduleTable
def search_Schedule(request):
context_dict = {}
if request.method == 'POST':
query = request.POST['course_name_search']
results = Schedules.objects.filter(course_name=query)
table = ScheduleTable(results)
if query:
context_dict['table'] = table
else:
context_dict['no_results'] = query
return render(request, "schedule/search_schedule.html", context_dict)
search_schedule.html
{% extends 'base.html' %}
{% load django_tables2 %}
{% block main_content %}
<form method="post" action="">
{% csrf_token %}
<label for="course_name_search">Course Name:</label>
<input type="text" name="course_name_search" id="course_name_search">
<input type="submit" name="submit">
</form>
<div id="result_panel">
{% if no_results %}
No results returned for <q>{{ no_results }}</q>
{% else %}
{% render_table table %}
{% endif %}
</div>
{% endblock %}
The error I'm getting is 'ValueError at /schedule/search_schedule/: Expected table or queryset, not str.' I'm pretty sure I followed the steps to the letter. What am I doing wrong?
Edit: Here's the traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/schedule/search_schedule/
Django Version: 1.10
Python Version: 3.6.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'registration',
'django_countries',
'localflavor',
'django_tables2',
'avtechpassport',
'students',
'billing',
'timesheet',
'wai_wdp',
'jobs',
'schedule']
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 /home/jerry22/PycharmProjects/avtechpassport_proj1/templates/schedule/search_schedule.html, error at line 38
Expected table or queryset, not str 28 : <form method="post" action="">
29 : {% csrf_token %}
30 : <label for="course_name_search">Course Name:</label>
31 : <input type="text" name="course_name_search" id="course_name_search">
32 : <input type="submit" name="submit">
33 : </form>
34 : <div id="result_panel">
35 : {% if no_results %}
36 : No results returned for <q>{{ no_results }}</q>
37 : {% else %}
38 : {% render_table table %}
39 : {% endif %}
40 : </div>
41 : {% endblock %}
Traceback:
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/jerry22/PycharmProjects/avtechpassport_proj1/schedule/views.py" in search_Schedule
81. return render(request, "schedule/search_schedule.html", context_dict)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/shortcuts.py" in render
30. content = loader.render_to_string(template_name, context, request, using=using)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/loader.py" in render_to_string
68. return template.render(context, request)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/backends/django.py" in render
66. return self.template.render(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/base.py" in render
208. return self._render(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/base.py" in _render
199. return self.nodelist.render(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/base.py" in render
994. bit = node.render_annotated(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/base.py" in render_annotated
961. return self.render(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/loader_tags.py" in render
174. return compiled_parent._render(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/base.py" in _render
199. return self.nodelist.render(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/base.py" in render
994. bit = node.render_annotated(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/base.py" in render_annotated
961. return self.render(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/loader_tags.py" in render
70. result = block.nodelist.render(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/base.py" in render
994. bit = node.render_annotated(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/base.py" in render_annotated
961. return self.render(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/defaulttags.py" in render
323. return nodelist.render(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/base.py" in render
994. bit = node.render_annotated(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/base.py" in render_annotated
961. return self.render(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django_tables2/templatetags/django_tables2.py" in render
132. raise ValueError('Expected table or queryset, not {}'.format(klass))
Exception Type: ValueError at /schedule/search_schedule/
Exception Value: Expected table or queryset, not str

For a GET request, {% if no_results %} will evaluate to False, so Django tries to render a non-existent table in the {% else %} block.
You could do something like this instead.
{% if table %}
{% render_table table %}
{% else %}
{% if no_results %}
No results returned for <q>{{ no_results }}</q>
{% else %}
Please enter a search
{% endif %}
{% endif %}

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.

(Django) DetailView template not displaying information

Within my maintenance app, I have six models. I will include only 2 of the models that are relevant towards this question. There is a list of equipment (Listview) which displays properly. However, I'm having a problem creating a DetailView for each equipment. When I go to the http://127.0.0.1:8000/maintenance/equipments/1 it should display all equipment instance (details) relevant to equipment 1 but it displays back the equipment list page, i.e, http://127.0.0.1:8000/maintenance/equipments/.
models.py
from django.db import models
class Equipment(models.Model):
"""
Model representing an Equipment (but not a specific type of equipment).
"""
title = models.CharField(max_length=200)
physicist = models.ForeignKey('Physicist', null=True, help_text= 'add information about the physicist')
technician = models.ForeignKey('Technician', null=True, help_text= 'add information about the technician')
# Physicist as a string rather than object because it hasn't been declared yet in the file.
features = models.TextField(max_length=1000, help_text='Enter a brief description of the features of the equipment')
machine_number = models.CharField('Number', max_length=30, null=True, help_text='Enter the Equipment number')
specialty = models.ForeignKey(Specialty, null=True, help_text='Select a specialty for an equipment')
# Specialty class has already been defined so we can specify the object above.
assigned_technician = models.CharField(max_length=50, null= True, blank=True)
#This is for the Technician who the repair of the Equipment is assigned to.
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('equipment-detail', args=[str(self.id)])
def display_specialty(self):
return ', '.join([ specialty.name for specialty in self.specialty.all()[:3] ])
display_specialty.short_description = 'Specialty'
class Meta:
ordering = ['-id']
class EquipmentInstance(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular equipment across the entire database")
equipment = models.ForeignKey('Equipment', on_delete=models.SET_NULL, null=True)
imprint = models.CharField(max_length=200)
due_date = models.DateField(null=True, blank=True)
delegate = models.ForeignKey('Physicist', on_delete=models.SET_NULL, null=True, blank=True)
def is_overdue(self):
if self.due_date and date.today() > self.due_date:
return True
return False
MAINTENANCE_STATUS = (
('p', 'Past Maintenance'),
('o', 'On Maintenance'),
('a', 'Available'),
('r', 'Reserved'),
)
status = models.CharField(max_length=1, choices = MAINTENANCE_STATUS, blank=True, default='m', help_text='Equipment availability')
class Meta:
ordering = ["due_date"]
permissions = (("can_mark_maintained", "Set equipment as maintained"),)
def __str__(self):
"""
String for representing the Model object
"""
return '{0} ({1})'.format(self.id,self.equipment.title)
maintanance/urls.py
from django.conf.urls import url
from qatrack.maintenance import views
from qatrack.maintenance import models
urlpatterns = [
url(r'^$', views.MDashboard, name='m_dash'),
url(r'^equipments/$', views.EquipmentListView.as_view(), name='equipments'),
url(r'^equipment(?P<pk>\d+)/$', views.EquipmentDetailView.as_view(), name='equipment-detail'),
]
views.py
from django.shortcuts import render
from django.views.generic import DetailView, ListView
from qatrack.maintenance import models
class EquipmentListView(ListView):
template_name = 'maintenance/equipment_list.html'
def get_queryset(self):
return models.Equipment.objects.all()
paginate_by = 10
class EquipmentDetailView(DetailView):
model = models.Equipment
template_name = 'maintenance/equipment_detail.html'
context_object_name = 'equipment'
equipment_list.html
{% extends "maintenance/m_base.html" %}
{% block body %}
<div class="row">
<div class="col-md-12">
<div class="box">
<h1>Equipment List</h1>
{% if equipment_list %}
<ul>
{% for equipment in equipment_list %}
<li>
{{ equipment.title }} ({{equipment.physicist}}, {{equipment.technician}})
</li>
{% endfor %}
</ul>
{% else %}
<p>There are no equipments in the database.</p>
{% endif %}
</div>
</div>
</div>
{% endblock body %}
equipment_detail.html
{% extends "maintenance/m_base.html" %}
{% block title %}Equipment Details{% endblock %}
{% block body %}
<h1>Title: {{ equipment.title }}</h1>
<h2>Machine Detail</h2>
<p><strong>Physicist:</strong> {{ equipment.physicist }}</p> <!-- physicist detail link not yet defined -->
<p><strong>Technician:</strong> {{ equipment.technician }}</p> <!-- technician detail link not yet defined -->
<p><strong>Features:</strong> {{ equipment.features }}</p>
<p><strong>Machine_number:</strong> {{ equipment.machine_number }}</p>
<p><strong>Specialty:</strong> {% for specialty in equipment.specialty.all %} {{ specialty }}{% if not forloop.last %}, {% endif %}{% endfor %}</p>
{% for type in equipment.equipmentinstance_set.all %}
<hr>
<p class="{% if type.status == 'a' %}text-success{% elif type.status == 'm' %}text-danger{% else %}text-warning{% endif %}">{{ type.get_status_display }}</p>
{% if type.status != 'a' %}<p><strong>Due to be maintained:</strong> {{type.due_date}}</p>{% endif %}
<p><strong>Imprint:</strong> {{type.imprint}}</p>
<p class="text-muted"><strong>Id:</strong> {{type.id}}</p>
{% endfor %}
</div>
{% endblock body %}
urls.py
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.views.generic.base import TemplateView, RedirectView
from django.contrib.staticfiles.templatetags.staticfiles import static as static_url
from django.contrib import admin
from qatrack.maintenance.views import get_data
admin.autodiscover()
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name="homepage.html"), name="home"),
url(r'^accounts/', include('qatrack.accounts.urls')),
url(r'^qa/', include('qatrack.qa.urls')),
url(r'^servicelog/', include('qatrack.service_log.urls')),
url(r'^parts/', include('qatrack.parts.urls')),
url(r'^units/', include('qatrack.units.urls')),
url(r'^issues/', include('qatrack.issue_tracker.urls')),
url(r'^maintenance/', include('qatrack.maintenance.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I have gone through a lot of questions similar to this here and applied them but I still can't get the DetailView to work. I will really appreciate any help. Thanks. After making changes I encountered this traceback error
Internal Server Error: /maintenance/equipment1/ Traceback (most recent
call last): File
"/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/urls/base.py",
line 77, in reverse
extra, resolver = resolver.namespace_dict[ns] KeyError: 'equipments'
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File
"/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/core/handlers/exception.py",
line 41, in inner
response = get_response(request) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/core/handlers/base.py",
line 217, in _get_response
response = self.process_exception_by_middleware(e, request) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/core/handlers/base.py",
line 215, in _get_response
response = response.render() File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/response.py",
line 107, in render
self.content = self.rendered_content File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/response.py",
line 84, in rendered_content
content = template.render(context, self._request) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/backends/django.py",
line 66, in render
return self.template.render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/base.py",
line 207, in render
return self._render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/test/utils.py",
line 107, in instrumented_test_render
return self.nodelist.render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/base.py",
line 990, in render
bit = node.render_annotated(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/base.py",
line 957, in render_annotated
return self.render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/loader_tags.py",
line 177, in render
return compiled_parent._render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/test/utils.py",
line 107, in instrumented_test_render
return self.nodelist.render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/base.py",
line 990, in render
bit = node.render_annotated(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/base.py",
line 957, in render_annotated
return self.render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/loader_tags.py",
line 177, in render
return compiled_parent._render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/test/utils.py",
line 107, in instrumented_test_render
return self.nodelist.render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/base.py",
line 990, in render
bit = node.render_annotated(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/base.py",
line 957, in render_annotated
return self.render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/loader_tags.py",
line 72, in render
result = block.nodelist.render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/base.py",
line 990, in render
bit = node.render_annotated(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/base.py",
line 957, in render_annotated
return self.render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/defaulttags.py",
line 322, in render
return nodelist.render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/base.py",
line 990, in render
bit = node.render_annotated(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/base.py",
line 957, in render_annotated
return self.render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/defaulttags.py",
line 458, in render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File
"/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/urls/base.py",
line 87, in reverse
raise NoReverseMatch("%s is not a registered namespace" % key) django.urls.exceptions.NoReverseMatch: 'equipments' is not a
registered namespace [14/May/2018 16:05:33] "GET
/maintenance/equipment1/ HTTP/1.1" 500 215728
Your url is not correct
instead of
url(r'^equipment(?:/(?P<pk>\d+))?/$', views.EquipmentDetailView.as_view(), name="equipment_detail"),
it should be:
url(r'^equipment/(?P<pk>\d+)/$', views.EquipmentDetailView.as_view(), name="equipment_detail"),
Update your DetailView with this:
class EquipmentDetailView(DetailView):
model = models.Equipment
template_name = 'maintenance/equipment_detail.html'
context_object_name = 'equipment'
You don't need to override default method if you are not doing anything extra than the DetailView offers.

Django Add Edit Form - Field has no attribute assigned to it?

Im trying to combine an add and edit form into one and am receiving an error The 'site_image' attribute has no file associated with it.
I could edit files but could not add files, but now when I load the site files page I am receiving the below error, I havent changed the model so am unsure as to why im receiving this error.
the list of files shouldn't really care if site_image is there or not as its set to blank and null?
my file model:
class SiteFiles(models.Model):
site_data = models.ForeignKey(SiteData, verbose_name="Site", on_delete=models.PROTECT)
site_image = models.ImageField(upload_to='site_files/', blank=True, null=True)
site_image_thumbnail = ImageSpecField(source='site_image',
processors=[ResizeToFill(200, 150)],
format='JPEG',
options={'quality': 60})
site_file = models.FileField(blank=True, upload_to=site_files_path, \
validators=[validate_file_extension])
file_name = models.CharField(max_length=200, verbose_name="File Name")
file_type = models.CharField(max_length=100, verbose_name='File Type', \
choices=settings.FILE_TYPE)
class Meta:
verbose_name = "Site Files"
verbose_name_plural = "Site Files"
def __str__(self):
return '%s | %s | %s ' % (self.site_data.location, self.site_data.location, self.file_name)
my forms.py
class FileForm(forms.ModelForm):
class Meta:
model = SiteFiles
fields = ['site_image', 'site_file', 'file_name','file_type']
def __init__(self, *args, **kwargs):
super(FileForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.form_id = 'file_form'
self.helper.form_method = 'POST'
self.helper.add_input(Submit('submit', 'Save', css_class='btn-primary'))
self.helper.layout = Layout(
Div(
Div(
Div(
Div(HTML('<i class="fa fa-camera-retro fa-fw"></i> Add File or Photo'), css_class='panel-heading'),
Div(
Field('site_image', placeholder='Image'),
Field('site_file', placeholder='File'),
Field('file_name', placeholder='Display Name'),
Div('file_type', title="File Type"),
css_class='panel-body'
),
css_class='panel panel-default',
),
css_class='col-lg-3'
),
css_class='row'
),
)
my views.py
#login_required
#user_passes_test(lambda u: u.has_perm('sites.add_sitefile'))
def add_edit_file(request, site_id, item_id=None):
from sites.forms import FileForm
from sites.models import SiteFiles
site_data = get_object_or_404(SiteData, pk=site_id)
# set edit values
if item_id:
item_data = get_object_or_404(SiteFiles, pk=item_id)
form_type = 'Edit'
form = FileForm(instance=item_data)
else:
# set add values
form = FileForm()
form_type = 'Add'
item_data = SiteFiles()
# set posting
if request.method == 'POST':
form = FileForm(request.POST,instance=item_data)
if form.is_valid():
form.instance.site_data = site_data
form.save()
return redirect('sites:site_detail_files', site_id)
return render(request, 'sites/add_edit_file.html', {
'add_edit_file_form': form,
'SiteName' : site_data.location,
'SiteID' : site_id,
'ItemID' : item_id,
'FormType' : form_type
})
Error:
Traceback:
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in _resolve_lookup
882. current = current[bit]
During handling of the above exception ('ImageFieldFile' object is not subscriptable), another exception occurred:
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _legacy_get_response
249. response = self._get_response(request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "/itapp/itapp/sites/views.py" in site_detail_files
311. 'active_files' : 'class="active"',
File "/usr/local/lib/python3.6/site-packages/django/shortcuts.py" in render
30. content = loader.render_to_string(template_name, context, request, using=using)
File "/usr/local/lib/python3.6/site-packages/django/template/loader.py" in render_to_string
68. return template.render(context, request)
File "/usr/local/lib/python3.6/site-packages/django/template/backends/django.py" in render
66. return self.template.render(context)
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in render
207. return self._render(context)
File "/usr/local/lib/python3.6/site-packages/django/test/utils.py" in instrumented_test_render
107. return self.nodelist.render(context)
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in render
990. bit = node.render_annotated(context)
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in render_annotated
957. return self.render(context)
File "/usr/local/lib/python3.6/site-packages/django/template/loader_tags.py" in render
177. return compiled_parent._render(context)
File "/usr/local/lib/python3.6/site-packages/django/test/utils.py" in instrumented_test_render
107. return self.nodelist.render(context)
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in render
990. bit = node.render_annotated(context)
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in render_annotated
957. return self.render(context)
File "/usr/local/lib/python3.6/site-packages/django/template/loader_tags.py" in render
177. return compiled_parent._render(context)
File "/usr/local/lib/python3.6/site-packages/django/test/utils.py" in instrumented_test_render
107. return self.nodelist.render(context)
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in render
990. bit = node.render_annotated(context)
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in render_annotated
957. return self.render(context)
File "/usr/local/lib/python3.6/site-packages/django/template/loader_tags.py" in render
72. result = block.nodelist.render(context)
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in render
990. bit = node.render_annotated(context)
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in render_annotated
957. return self.render(context)
File "/usr/local/lib/python3.6/site-packages/django/template/defaulttags.py" in render
216. nodelist.append(node.render_annotated(context))
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in render_annotated
957. return self.render(context)
File "/usr/local/lib/python3.6/site-packages/django/template/library.py" in render
202. resolved_args, resolved_kwargs = self.get_resolved_arguments(context)
File "/usr/local/lib/python3.6/site-packages/django/template/library.py" in get_resolved_arguments
188. resolved_args = [var.resolve(context) for var in self.args]
File "/usr/local/lib/python3.6/site-packages/django/template/library.py" in <listcomp>
188. resolved_args = [var.resolve(context) for var in self.args]
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in resolve
708. obj = self.var.resolve(context)
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in resolve
849. value = self._resolve_lookup(context)
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in _resolve_lookup
890. current = getattr(current, bit)
File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/files.py" in url
69. self._require_file()
File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/files.py" in _require_file
46. raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
Exception Type: ValueError at /sites/site/files/7
Exception Value: The 'site_image' attribute has no file associated with it.
EDIT:
site_details_files:
#login_required
def site_detail_files(request, site_id):
files = SiteFiles.objects.filter(site_data__id=site_id)
try:
site = files[0].site_data
except:
site = get_object_or_404(SiteData, pk=site_id)
return render(request, 'sites/site_detail_files.html', {
'Files': files,
'SiteName' : site.location,
'SiteID' : site.id,
'PageType' : 'files',
'active_files' : 'class="active"',
})
template:
{% block content %}
<div class="col-lg-9">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-camera fa-fw"></i> Photos
</div>
<div class="panel-body">
{% get_file_type Files 'Cabinet Photo' as photos %}
{% for file in photos %}
<div class="img-item">
<div class="img">
<a class="image-float-left" id="" href="{% signed_url file.site_image.url %}" target="_blank">
<img src="{% signed_url file.site_image_thumbnail.url %}" alt="" />
</a>
</div>
<div class="img-text">
{{ file.file_name }}
<div class="img-edit" >
<a href="{% url 'sites:edit_file' SiteID file.id %}" class="edit-icon">
<i class="fa fa-edit"></i>
</a>
</div>
</div>
</div>
<!-- /.img-item-->
{% endfor %}
</div>
<!-- /.panel-body-->
</div>
<!-- /.panel-->
</div>
<!-- /.col-lg-9 -->
<div class="col-lg-3">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-file-text-o fa-fw"></i> Files
</div>
<div class="panel-body">
{% exclude_file_type Files 'Cabinet Photo' as site_files %}
{% for file in site_files %}
<ul>
{% if file.file_type != "Cabinet Photo" %}
{% if file.site_file %}
<li>
<a href="{% url 'sites:edit_file' SiteID file.id %}" class="edit-icon">
<i class="fa fa-edit fa-1x"></i>
</a>
{{ file.file_name }}
</li>
{% endif %}
{% if file.site_image %}
<li>
<a href="{{% url 'sites:edit_file' SiteID file.id %}" class="edit-icon">
<i class="fa fa-edit"></i>
</a>
{{ file.file_name }}
</li>
{% endif %}
{% endif %}
</ul>
{% endfor %}
</div>
<!-- /.panel-body-->
</div>
<!-- /.panel-->
</div>
<!-- /.col-lg-9 -->
{% endblock %}
You need to pass request.FILES to the form when uploading files.
form = FileForm(request.POST, request.FILES, instance=item_data)
Make sure that you set enctype="multipart/form-data" in the template as well.
See the docs on file uploads for more info.
However, these changes won't solve your error, since it is coming from a different view site_detail_files. It looks as if you are using file.site_image.url in the template without checking file.site_image first. You should add an extra if block:
{% for file in photos %}
...
{% if file.site_image %}
...
<a class="image-float-left" id="" href="{% signed_url file.site_image.url %}" target="_blank">
...
{% endif %}
{% endfor %}

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

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.

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