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.
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.
Reverse for 'job_category' with keyword arguments '{'id': <Category: Government>}' not found. 1 pattern(s) tried: ['job_category/(?P<category_slug>[^/]+)/$']
{% extends 'base1.html' %}
{% block content %}
<div class="left col-sm-4" style="float:left; width: 360px;">
<h6 class="p-2" style="background:#A9CCE3; color:#2F4F4F;">JOB CATEGORIES</h6>
<ul class="list-group">
{% for x in categories %}
<li class="list-group-item c1 list-group-item-action" style="color: rgb(2,96,170);">
<div class="p-2">
<h7 class="card-title">
{{x.name}}
</h7>
</div>
<div class="overlay1"></div>
</li>
{% endfor %}
</ul>
</div>
<div class="right col-sm-8" style="float: right; width:825px;">
<!--{% if category %}{{category.name}}{% endif %} !-->
<div class="row container-fluid">
{% for job in jobs %}
<div class="col-sm-3 mt-3">
<div class="card c1">
<div class="overlay1"></div>
<div class="card-body">
<h5 class="card-title" style="color: rgb(2,96,170);">
{{job.post}}</h5>
<h6 class="card-text" style="color: rgb(85, 85, 85);">
{{job.job_id.comp_name}}</h6>
<p><i class="fas fa-map-marker-alt mr-1"></i>{{job.address}}<i
class="far fa-calendar-alt ml-3 mr-1"></i>{{job.todate|date:'d M, Y'}}</p>
<a href="{% url 'job_detail' job.job_id.id %}" class="btn btn-primary btn-sm right"
style="position:relative; float:right;">View more</a>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock content %}
views.py:
def job_category(request, category_slug=None):
category = None
job_requirements = []
categories = Category.objects.all()
jobs = Job.objects.all()
if category_slug:
category = Category.objects.get(slug=category_slug)
print(category.slug)
jobs = Job.objects.filter(job_category=category.slug)
for job in jobs:
job_requirements.append(JobRequirements.objects.get(job_id=job))
return render(request, 'JobCategory/category.html', {'categories': categories,
'jobs': job_requirements})
urls.py:
path('job_category/<str:category_slug>/', views.job_category, name='job_category'),
Models.py:
class Category(models.Model):
name = models.CharField(max_length=40, blank=True, null=True)
slug = models.CharField(max_length=4, unique=True)
def __str__(self):
return self.name
def get_absolute_path(self):
return reverse('job_category', kwargs={'category_slug': self.slug})
I've been trying to filter my page category wise. I cannot find where my mistake is at and can't simply decode this error message. I'm very new to this. Please help!
(Update) Traceback:
Internal Server Error: /job_category/IT/
Traceback (most recent call last):
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\DELL\PycharmProjects\RECRUIT\Home\views.py", line 33, in job_category
'jobs': job_requirements})
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\base.py", line 171, in render
return self._render(context)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\base.py", line 163, in _render
return self.nodelist.render(context)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\base.py", line 936, in render
bit = node.render_annotated(context)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\base.py", line 903, in render_annotated
return self.render(context)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\loader_tags.py", line 150, in render
return compiled_parent._render(context)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\base.py", line 163, in _render
return self.nodelist.render(context)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\base.py", line 936, in render
bit = node.render_annotated(context)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\base.py", line 903, in render_annotated
return self.render(context)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\loader_tags.py", line 62, in render
result = block.nodelist.render(context)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\base.py", line 936, in render
bit = node.render_annotated(context)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\base.py", line 903, in render_annotated
return self.render(context)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\defaulttags.py", line 443, in render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\urls\base.py", line 87, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 677, in _reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'job_category' with keyword arguments '{'id': <Category: Government>}' not found. 1 pattern(s) tried: ['
job_category/(?P<category_slug>[^/]+)/$']
[14/Dec/2020 11:08:58] "GET /job_category/IT/ HTTP/1.1" 500 173336
I solved this problem by replacing my kwargs 'category_slug' with 'id'. But, I have no clue why it didn't take category_slug as an kwargs.
class Category(models.Model):
name = models.CharField(max_length=40, blank=True, null=True)
slug = models.CharField(max_length=4, unique=True)
def __str__(self):
return self.name
def get_absolute_path(self):
return reverse('job_category', kwargs={'id': self.slug})
urls.py
path('job_category/<str:id>/', views.job_category, name='job_category')
views.py
def job_category(request, id=None):
category = None
job_requirements = []
categories = Category.objects.all()
jobs = Job.objects.all()
if id:
category = Category.objects.get(slug=id)
print(category.slug)
jobs = Job.objects.filter(job_category=category.slug)
for job in jobs:
job_requirements.append(JobRequirements.objects.get(job_id=job))
print(job_requirements)
return render(request, 'JobCategory/category.html', {'categories': categories,
'jobs': job_requirements})
I'm trying to create a searchbar in my blog in python, but I'm receiving the following error: Reverse for 'article-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['app1/article/(?P[0-9]+)$'] and I'm not sure why, so here's the code so you guys can see what's going on here:
Traceback
Traceback (most recent call last):
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\snin2\Desktop\basura\lapagina\app1\views.py", line 187, in searchbar
return render(request, 'app1/search.html', {'query':query, 'results':results})
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\backends\django.py", line 61,
in render
return self.template.render(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 170, in render
return self._render(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 162, in _render
return self.nodelist.render(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\loader_tags.py", line 150, in
render
return compiled_parent._render(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 162, in _render
return self.nodelist.render(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\loader_tags.py", line 62, in render
result = block.nodelist.render(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\defaulttags.py", line 312, in
render
return nodelist.render(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\defaulttags.py", line 211, in
render
nodelist.append(node.render_annotated(context))
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\defaulttags.py", line 446, in
render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\urls\base.py", line 87, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\urls\resolvers.py", line 685, in _reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'article-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['app1/article/(?P<pk>[0-9]+)$']
Models.py
class StockNames(models.Model):
name = models.CharField(max_length=255)
symbol = models.CharField(max_length=255)
def __str__(self):
return self.symbol
class Post(models.Model):
title = models.CharField(max_length= 255)
header_image = models.ImageField(null = True, blank = True, upload_to = 'images/')
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = RichTextField(blank = True, null = True)
#body = models.TextField()
post_date = models.DateField(auto_now_add=True)
category = models.CharField(max_length=255, default='coding')
snippet = models.CharField(max_length=255)
likes = models.ManyToManyField(User, related_name = 'blog_posts')
stock = models.ForeignKey(StockNames, null=True, on_delete = models.CASCADE)
def total_likes(self):
return self.likes.count()
def __str__(self):
return self.title + ' | ' + str(self.author)
def get_absolute_url(self):
return reverse('app1:article-detail', args=(self.id,))
Views.py
def searchbar(request):
query = None
results = []
if request.method == 'GET':
query=request.GET.get("search")
results= Post.objects.filter(Q(title__icontains=query) | Q(stock__symbol__icontains=query))
return render(request, 'app1/search.html', {'query':query, 'results':results})
search.html
{% extends "app1/base.html" %}
{% block body_block %}
<div class="container">
<h1>Search Page</h1>
{% if query %}
<h3>{% with results.count as total_results %}
Found {{total_results}} total results
{% endwith %}
</h3>
{% for x in results %}
<li>{{sym}} -
{{post.author}} - <small>{{post.post_date}}</small> -
{% if user.is_authenticated %}
<small>Edit</small><small>
- Delete
</small></li>
{% endif %}
</div>
{% empty %}
<h1>There's no query</h1>
{% endfor %}
{% else %}
<h3>Error in your query</h3>
{% endif %}
{% endblock %}
base.html (specifically the search input)
<form action="{% url 'app1:searchbar' %}" class="form-inline my-2 my-lg-0" method="GET">
<input name="search" class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search", name='search'>
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
urls.py (the last one)
app_name = 'app1'
urlpatterns = [
path('post/', PostView.as_view(), name = 'Post'),
path('article/<int:pk>', ArticleDetailView.as_view(), name = 'article-detail'),
path('add_post/<str:sym>',AddPostView.as_view(), name='addpost'),
path('update_post/<int:pk>', UpdatePostView.as_view(), name = 'updatepost'),
path('delete_post/<int:pk>', DeletePostView.as_view(), name = 'deletepost'),
path('add_category/', AddCategoryView.as_view(), name = 'add_category'),
path('category/<str:cats>/', views.CategoryView, name = 'category'),
path('category-list/', views.CategoryListView, name ='category-list'),
path('like/<int:pk>/', views.LikeView, name = 'like_post'),
path('my_posts/', views.MyPostsView.as_view(), name = 'my_posts'),
path('article/<int:pk>/add_comment/', AddCommentView.as_view(), name = 'add_comment'),
path('update_comment/<int:pk>', UpdateCommentView.as_view(), name = 'updatecomment'),
path('delete_comment/<int:pk>', DeleteCommentView.as_view(), name = 'deletecomment'),
path('stock/<str:sym>/', views.StockView, name = 'stock'),
path('searchbar/', views.searchbar, name = 'searchbar'),
]
Thanks in advance!
{% for post in results %}
<li>{{sym}} -
{% if user.is_authenticated %}
<small>Edit</small><small>
- Delete
</small></li>
{% endif %}
<a href="{% url 'app1:article-detail' post.pk %}">
here 'post' is not declared/contexted/retrieved from db.thats why you are getting error.
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'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 %}