Home > database >  getting the error "The QuerySet value for an exact lookup must be limited to one result using s
getting the error "The QuerySet value for an exact lookup must be limited to one result using s

Time:01-16

I am trying to create a lms with django. So I have a separate model for the teachers who can upload the courses, and another model for courses. The code is below: models.py

class teacher(models.Model):
    name=models.ForeignKey(User, on_delete= models.CASCADE)
    area=models.ManyToManyField(subject)
    description=RichTextField()


class course(models.Model):
    title=models.CharField(max_length=500)
    areas=models.ManyToManyField(subject)
    description=RichTextField()
    instructor=models.ForeignKey(teacher, on_delete= models.CASCADE)
    material=models.CharField(max_length=1000)

    def __str__(self):
        return self.title

In my views.py file:

instr=teacher.objects.filter(name=request.user)
data2=models.course.objects.filter(instructor__name__username=instr)
    
return render(request, "course/profile.html", {'datas':a, 'courses': data, 'creations':data2})

in the templete:

<div ><label >Created Courses</label>
                {% for data in creations %}
                <form action="/course/" method="GET">
                    <div >
                      <div  style="width: 30rem; height: 30rem;">
                        <div >
                          <h5 >{{data.title}}</h5>
                          <h6 class='card-title'>Uploaded by {{data.instructor.name}}</h6>
                          <button type="submit"  name="s" value="{{data.pk}}">Go to Course</button>
                        </div>
                      </div>
                      
                       
                      </div>
                    
                    
                  </form>
                {% endfor %}
            </div>

I get the error: enter image description here

What is the way to remove this issue?

CodePudding user response:

instr is a QuerySet you can't add it to the filter directly like you did. You can get list of courses directly by using request.user

data2=models.course.objects.filter(instructor__name=request.user)
return render(request, "course/profile.html", {'datas':a, 'courses': data, 'creations':data2})

if you want to get the teacher first then you have to use get:

instr=teacher.objects.get(name=request.user)   
data2=models.course.objects.filter(instructor=instr)

return render(request, "course/profile.html", {'datas':a, 'courses': data, 'creations':data2})
  •  Tags:  
  • Related