1 回答

TA貢獻(xiàn)1909條經(jīng)驗(yàn) 獲得超7個(gè)贊
該user字段Course指的是Student對(duì)象,而不是User對(duì)象,因此您不能使用request.user它。
但是,您可以查詢Coursewhere the useris a Studentwhere the useris request.user:
class Program_structure(generic.View):
def get(self, *args, **kwargs):
profile = Student.objects.all()
program_structure = Course.objects.filter(user__user=self.request.user)
context = {
'test':program_structure,
'profile':profile,
}
return render(self.request, 'program_structure.html', context)
您可能還想設(shè)置profile為Student用戶的對(duì)象。在這種情況下,您可以在過(guò)濾s時(shí)重用:profileCourse
from django.shortcuts import get_object_or_404
class Program_structure(generic.View):
def get(self, *args, **kwargs):
profile = get_object_or_404(Student, user=request.user)
program_structure = Course.objects.filter(user=profile)
context = {
'test':program_structure,
'profile':profile,
}
return render(self.request, 'program_structure.html', context)
將該user字段重命名為student:
class Course(models.Model):
student = models.ForeignKey(
Student,
on_delete=models.SET_NULL,
null=True
)
# …
因?yàn)檫@清楚地表明這是 a Student,而不是 a User。在這種情況下,您可以使用以下內(nèi)容進(jìn)行過(guò)濾:
from django.shortcuts import get_object_or_404
class Program_structure(generic.View):
def get(self, *args, **kwargs):
profile = get_object_or_404(Student, user=request.user)
program_structure = Course.objects.filter(student=profile)
context = {
'test':program_structure,
'profile':profile,
}
return render(self.request, 'program_structure.html', context)
添加回答
舉報(bào)