当我想使用views.py时,我给出'QuerySet'对象没有属性错误

问题描述 投票:0回答:1

我想用下一个和上一个课程打开课程详细信息,但我的尝试不起作用,我给出了 404 错误,当我删除尝试时,除了我给出“QuerySet”对象没有属性错误,并说错误来自 counted_viewsenter image description here

views.py:

```
def course_detail(request,id):
    try:
        course = Courses.objects.get(id=id)
        id_list = []
        course = Courses.objects.filter(status = True)
        for cr in course :
            id_list.append(cr.id)
        
        if id_list[0] == id:
            next_course = Courses.objects.get(id=id_list[1])
            previous_course =None

        elif id_list[-1] == id:
            next_course = None
            previous_course = Courses.objects.get(id=id_list[-2])

        else:
            next_course = Courses.objects.get(id=id_list[id_list.index(id)+1])
            previous_course = Courses.objects.get(id=id_list[id_list.index(id)-1])



        course.counted_views += 1
        course.save()
        context = {
            'course': course,
            'next_course': next_course,
            'previous_course': previous_course,
        }
        return render(request,"courses/course-details.html",context=context)
    except:
        return render(request,'courses/404.html')
```
urls.py:
```
from django.urls import path
from .views import *

app_name = 'course'

urlpatterns = [
    path('',Maincourse,name='courses'),
    path('category/<str:cat>',Maincourse,name='course_cat'),
    path('teacher/<str:teacher>',Maincourse,name='course_teacher'),
    path('search/',Maincourse,name='course_search'),
    path('course_detail/<int:id>',course_detail,name='course_detail'),
]```

models.py:

```class Courses(models.Model):
    title = models.CharField(max_length=40)
    content = models.TextField(max_length=1000)
    teacher = models.ForeignKey(Trainer,on_delete=models.CASCADE)
    price = models.IntegerField(default=0)
    image = models.ImageField(upload_to='courses',default='default.jpg')
    category = models.ManyToManyField(Category)
    counted_views = models.IntegerField(default=0)
    counted_likes = models.IntegerField(default=0)
    status = models.BooleanField(default=False)
    created_date = models.DateTimeField(auto_now_add = True)
    updated_date = models.DateTimeField(auto_now = True)
    available_seats = models.IntegerField(default = 0)
    schedule = models.DateTimeField(default=datetime.datetime.now())
```

enter image description here

python django view
1个回答
0
投票

您最初声明了一个变量

course
,用于获取一个对象,但随后将其重新分配给一个查询集,该查询集现在不再是一个对象,而是一个对象列表。您可以从以下位置编辑此行:

course = Courses.objects.filter(status = True)

致:

courses = Courses.objects.filter(status = True)
id_list = [cr.id for cr in courses]

顺便说一句,按照惯例,模型以单数命名,因此

Course
而不是
Courses

© www.soinside.com 2019 - 2024. All rights reserved.