Does not exist. No exception supplied error - python

I have the following class based view.
class AllPluginsView(ListView):
queryset = get_models(get_app('plugins'))
template_name="console/plugins/plugins.html"
context_object_name = "objects"
And following template,
{% for object in objects %}
<tr>
{% if object %}
<td>{{ object }}</td>
{% endif %}
</tr>
{% endfor %}
When I ask for the page, i get DoesNotExist at /path/to/plugins
No exception supplied. error. Any ideas ?
urlpatterns = patterns('',
url(r'^$', AllPluginsView.as_view(),name='all-plugins'),
)

Perhaps it's an import order thing? Try using get_queryset instead.
class AllPluginsView(ListView):
template_name="console/plugins/plugins.html"
context_object_name = "objects"
def get_queryset(self):
return get_models(get_app('plugins'))

Related

When I access the page, nothing appears

I want to use the following code to filter the data in models.py in views.py and output the Today_list to today.html, but when I open this url, nothing is displayed. What is the problem?
class Post(models.Model):
created =models.DateTimeField(auto_now_add=True,editable=False,blank=False,null=False)
title =models.CharField(max_length=255,blank=False,null=False)
body =models.TextField(blank=True,null=False)
def __str__(self):
return self.title
views.py
from Todolist import models
from django.views.generic import ListView
from django.utils import timezone
class TodayView(ListView):
model = models.Post
template_name ='Todolist/today.html'
def get_queryset(self):
Today_list= models.Post.objects.filter(
created=timezone.now()).order_by('-id')
return Today_list
todaylist.html
{% extends "Todolist/base.html" %}
{% block content %}
{% for item in Today_list %}
<tr>
<td>{{item.title}}</td>
</tr>
{% endfor %}
{% endblock %}
urls.py
urlpatterns=[
path('today/' ,views.TodayView.as_view() ,name='today')
]
use get_context_data to add Today_list to context
ref : https://docs.djangoproject.com/en/4.1/ref/class-based-views/generic-display/
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['Today_list'] = self.get_queryset()
return context
or you can simply use in template model.name_list in your case it will be post_list instead of today_list
{% extends "Todolist/base.html" %}
{% block content %}
{% for item in post_list %}
<tr>
<td>{{item.title}}</td>
</tr>
{% endfor %}
{% endblock %}
problem is where you want objects that created today, but your queryset filter just right now, not today.
So to achieve today's posts, you can do this:
from django.utils import timezone
def get_queryset(self):
Today_list = models.Post.objects.filter(
created__gte=timezone.now().replace(hour=0, minute=0, second=0),
created__lte=timezone.now().replace(hour=23, minute=59, second=59)
).order_by('-id')
return Today_list
this queryset returns objects that have been created today.

Django 'model' object is not iterable

I have a table which shows me the employees registered. I want to generate a simple HTML page according to their DB which includes their name, id, designation, etc.
To do so, I pass an id to the view so it can get the respective user's details and show me. Everything works fine until the error occurs object is not iterable. Here is my code below.
report.html
{% if emp_item %}
{% for some in emp_item %}
<title> {{ some.employee_name }} Report</title>
<h3>{{ some.employee_name }}</h3>
<table style="width:30%" border="4">
<td>{{some.id}}</td>
<td>{{some.Annual_leave}} </td>
<td>{{some.Sick_leave}} </td>
<td>{{some.allowed}} </td>
</table>
{% endfor %}
<h2>No User</h2>
{% else %}
{% endif %}
views.py
#staff_member_required # for admin login required
def report(request, id):
emp_item = Employee.objects.get(id=id)
context = {'emp_item': emp_item}
return render(request, 'projectfiles/report.html', context)
urls.py
url(r'^(?i)Rejectleaves/$', views.rejected_leave_show,
name='Reject_show'), # user leaves
url(r'^(?i)report/(?P<id>\d+)$', views.report,
name='Report'), # user Report
models.py
class Employee(models.Model):
allowed = models.BooleanField(default=True)
employee_name = models.OneToOneField(User, on_delete = models.CASCADE)
employee_designation = models.CharField(max_length = 5)
employee_department = models.CharField(max_length = 5)
Annual_leave = models.PositiveSmallIntegerField(default=5)
Sick_leave = models.PositiveSmallIntegerField(default=5)
I want to see each individual user's data according to the process they have made.
Change Employee.objects.get(id=id) to Employee.objects.filter(id=id)
"filter() will always give you a QuerySet" - it's iterable
get() - return single object and it's not iterable
You are iterating over emp_item as an object list. But it is an object as Employee.objects.get(id=id) returns a single object rather than a queryset.
So what you need to do is remove the for-loop from the template as:
{% if emp_item %}
<title> {{ emp_item.employee_name }} Report</title>
<h3>{{ emp_item.employee_name }}</h3>
...and so on
{% else %}
<h2>No User</h2>
{% endif %}
But if you use get while querying, there is a higher chance that you can get an exception of DoesNotExist. So it is better if you can use Employee.objects.filter(id=id) to avoid any exceptions.
The {% if emp_item %} in your template is of no use if you are querying using get.
For better use, you can use get while querying and send a message to the template if exception occurs. For example:
def report(request, id):
try:
emp_item = Employee.objects.get(id=id)
return render(request, 'projectfiles/report.html', {'emp_item':emp_item})
except Employee.DoesNotExist:
return render(request, 'projectfiles/report.html', {'error': 'No data found.'})
Then in template:
{% if error %}
{{ error }}
{% else %}
<title> {{ emp_item.employee_name }} Report</title>
.... and so on to display other data
{% endif %}
I got the same error below:
TypeError: 'Category' object is not iterable
Because I assigned the object made by get() to category__in as shown below:
# Here # Here
Product.objects.filter(category__in=Category.objects.get(pk=1))
So, I assigned the queryset made by filter() to category__in as shown below, then the error was solved:
# Here
Product.objects.filter(category__in=Category.objects.filter(pk=1))
Or, I removed __in from category__in as shown below, then the error was solved:
# ↓ "__in" is removed
Product.objects.filter(category=Category.objects.get(pk=1))

Delete user directly from html template

I want to create a management page where an admin can delete users. I have succesfully made it list created users, but now i'm struggeling with how to create a deleteView to delete the user entirely from my django project.
Views.py
def index(request):
users = User.objects.all()
return render(request, 'EditUser.html',{'userlist':users})
def deletefunction(request,User =None):
object = User.objects.get(id=User)
object.delete()
return render(request,'EditUser.html')
Project urls.py
from edit_user.views import deletefunction
urlpatterns = [
path('admin/', admin.site.urls),
path('management', include('management.urls')),
path('management/create', include('signup.urls')),
path('management/edit', include('edit_user.urls')),
path('^delete/(?P<User>[0-9]+)/$', deletefunction, name='delete_view'),
]
HTML code
<div class="container">
{% for item in userlist %}
<tr>
<td>{{ item.username }}</td>delete
</tr>
{% endfor %}
</div>
As of right now when i'm trying to load my page i'm receiving this exception.
Reverse for 'deletefunction' not found. 'deletefunction' is not a
valid view function or pattern name.
def deletefunction(request, user_id):
object = User.objects.get(id=user_id)
object.delete()
users = User.objects.all()
return render(request,'EditUser.html', {'userlist': users})
and
<div class="container">
{% for item in userlist %}
<tr>
<td>{{ item.username }}</td>delete
</tr>
{% endfor %}
</div>
I think you should delete EditUser in href. Because you url in project urls.py(not EditUser urls ). So django looks EditUser app_name but they cant find.
Also you had not determineted 'User'.And you url name "delete_view" but you send view name.Can you change like this?Maybe work.
<td>{{ item.username }}</td>delete

Ordering Users in a Django ManyToManyField

I have a model that has a ManyToManyField of Users:
models.py
class Excuse(models.Model):
students = models.ManyToManyField(User)
reason = models.CharField(max_length=50)
views.py
def excuse_list(request, block_id=None):
queryset = Excuse.objects.all().prefetch_related('students')
context = {
"object_list": queryset,
}
return render(request, "excuses/excuse_list.html", context)
Template (excuse_list.html)
...
{% for excuse in object_list %}
<tr>
<td>{{ excuse.reason }}</td>
<td>
{% for student in excuse.students.all %}
{{student.get_full_name}};
{% endfor %}
</td>
</tr>
{% endfor %}
...
How can I sort the User set (excuse.students.all) alphabetically by a User field, for example: user.last_name?
you can do this just changing your views.py with this:
queryset = Excuse.objects.all().prefetch_related(
Prefetch('students', queryset=User.objects.order_by('lastname')))
remember to import User model!
You can create a method in your Excuse model, that will return a sorted students set:
def get_sorted_students(self):
return self.students.all().order_by('last_name')
And then in your template use excuse.get_sorted_students instead of excuse.students.all
Alternatively, you could use a custom template tag to render the list of students.

Django form field issue with model formset

I'm having an issue with rendering individual form fields in a template. I have a model formset that I'm re-ordering after creation to make displaying a little easier on the template. Nothing too complicated, but rendering the form fields isn't working. You can see in the template where I try and render {{ form.train }}, but nothing shows up in the output. However, the form is definitely there because {{ form.instance.user.name }} works correctly.
I opened up PDB and inspected the form variable that I'm adding into the dictionary, and it says <django.forms.widgets.ScheduleForm object at 0x10c58bc50>. I'm not sure if that helps or not, but I wanted to provide as much info as possible.
The Model Form
class ScheduleForm(ModelForm):
class Meta:
model = models.Schedule
fields = [
'train',
'semi',
'tri_axle',
'flow_boy',
'misc',
'material',
'notes'
]
views.py
formset_fields = ('train','semi','tri_axle','flow_boy','misc','material','notes')
ScheduleFormSet = modelformset_factory(models.Schedule, fields=formset_fields, extra=0)
formset = ScheduleFormSet(queryset=queryset)
# Getting form in the right format
ordered_forms = {}
for form in formset:
# Make sure the job exists on the object
if not form.instance.job.number in ordered_forms:
ordered_forms[form.instance.job.number] = {}
# Make sure the user exists on the object
if not form.instance.user.name in ordered_forms[form.instance.job.number]:
ordered_forms[form.instance.job.number][form.instance.user.name] = []
# Append to correct place.
ordered_forms[form.instance.job.number][form.instance.user.name].append(form)
# Dict will look like
# { 'jobID' : { 'user' : [form1,form2,form3] } }
Template
{% for job, users in ordered_forms.items %}
<h2>{{ job }}</h2>
{% for user, forms in users %}
<table class='table striped'>
<thead>
<tr>
<th>{{ user }}</th>
<th>Train</th>
<th>Semi</th>
<th>Tri-Axle</th>
<th>Flow Boy</th>
<th>Misc</th>
<th>Material</th>
<th>Notes</th>
<th></th>
</tr>
</thead>
<tbody>
{% for form in forms %}
<tr>
<td>{{ form.instance.broker.name }}</td>
<td>{{ form.train }}</td>
<td>Semi</td>
<td>Tri-Axle</td>
<td>Flow Boy</td>
<td>Misc</td>
<td>Material</td>
<td>Notes</td>
<td></td>
</tr>
{% endfor %}
</tbody>
</table>
{% endfor %}
{% endfor %}
Turns out I forgot to add .items to {% for user, forms in users %}.
{% for job, users in ordered_forms.items %}
<h2>{{ job }}</h2>
{% for user, forms in users.items %}
<table class='table striped'>
....
{% endfor %}
{% endfor %}

Categories

Resources