gpt4 book ai didi

python - 获取某些值以 django 形式出现

转载 作者:行者123 更新时间:2023-12-01 02:55:58 24 4
gpt4 key购买 nike

Image displaying issue

所附图片显示了我当前的问题。图中的 Math 270 和 Math 280 是由另一位用户创建的,而不是创建 Jays 类(class)的 Jay。然而,其他用户当前已登录,而不是 Jay。我如何才能只让登录用户(而不是 Jay)创建的类(class)出现在该下拉菜单中?

在我看来,我有以下尝试来解决这个问题:

class CreateQuestion(LoginRequiredMixin, CreateView):
model = Question
fields = ["title", "question", 'classe']
template_name = "attendance_test/add_test.html"

def form_valid(self, form):
form.instance.instructor = self.request.user
return super(CreateQuestion, self).form_valid(form)

def get_context_data(self, **kwargs):
context = super(CreateQuestion, self).get_context_data(**kwargs)
context['classe'] = Classe.objects.filter(professor=self.request.user.id)
return context

def get_initial(self):
return { 'classe': Classe.objects.filter(professor=self.request.user.id) }

我的问题模型:

class Question(models.Model):
title = models.CharField(max_length=100)
question = models.TextField(max_length=500)
date_pub = models.DateTimeField(auto_now_add=True)
instructor = models.ForeignKey(Teacher, on_delete=models.CASCADE, default="")
# this is where all the courses are showing up, I only want those
# created by the "instructor" to show up, not all instructors
classe = models.ForeignKey(Classe, on_delete=models.CASCADE, null=True)

def professor_classes(self):
return Classe.objects.filter(professor=self.professor)

教师模型:

class Teacher(User):  
isProfessor = models.BooleanField(default=False)
professor_courses = models.ForeignKey('Classe', on_delete=models.CASCADE, null=True)

如果有多达 1000 个类,但讲师只考虑了 4 个,那么这个问题就会成为问题,当 996 与它们无关时,显示所有 1000 个类是没有意义的。根据记录,我之前问过这个问题,我得到了答案,但我仍然无法解决它。

最佳答案

def get_form(self, form_class):
form = super(CreateQuestion, self).get_form(form_class)
form.fields['classe']= Classe.objects.filter(professor=self.request.user.id)
return form

你可以尝试这样的事情

关于python - 获取某些值以 django 形式出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44222893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com